python3 RuntimeError: dictionary changed size during iteration
python2
keys 先对字典进行 copy,从而在修改字典时,也能进行迭代
headerTable = {}
minSup = 1
for k in headerTable.keys():
if headerTable[k] < minSup:
del(headerTable[k])
python3
Python 3.x 的 keys 返回的是iterator 而非列表,导致当修改字典时,无法迭代。所以,可以使用list 强制将字典进行copy,转换成列表。
headerTable = {}
minSup = 1
for k in list(headerTable):
if headerTable[k] < minSup:
del(headerTable[k])
How to avoid “RuntimeError: dictionary changed size during iteration” error?
本文介绍了如何在Python中避免在遍历字典时修改字典导致的运行时错误。针对Python 2与Python 3的不同特性,给出了两种解决方法:Python 2中可以直接迭代字典的keys;而Python 3中需要先将keys转为列表再进行迭代。
2119

被折叠的 条评论
为什么被折叠?



