我浏览了与此主题相关的答案数据库,但找不到答案,本质上我正在循环字典,我得到"字典更改大小"运行时错误,但我弹出一个键和值并在迭代恢复之前插入另一个键和值。
for patterns in dict_copy.keys():
new_tuple = ()
for items in range(len(patterns)):
if patters[items] not in exclusion:
new_tuple += (patterns[items],)
dict_copy[new_tuple] = dict_copy.get(patterns)
dict_copy.pop(patterns)
我正在使用的词典的形式是:{("A","B","C","D"):4,("B","A","C","D") "2...}我几乎只是对它认为我正在追逐字典大小的事实感到困惑
该错误略有误导性。它试图告诉你的是,在迭代字典时,你不应该进行任何结构更改(插入/删除)。
解决此问题的一种简单方法是将结果放入单独的字典中:
new_dict = {}
for patterns in dict_copy.keys():
new_tuple = ()
for items in range(len(patterns)):
if patters[items] not in exclusion:
new_tuple += (patterns[items],)
new_dict[new_tuple] = dict_copy.get(patterns)
dict_copy = new_dict
我弹出一个键和值,并在 迭代恢复。
这并不重要。迭代数据结构时无法更改数据结构。Python的迭代器感到困惑(-:这不是字典的大小,而是它的内容。(在其他编程语言中也是如此...