python3 RuntimeError: dictionary changed size during iteration

来源:互联网 发布:怎样连接网络电视 编辑:程序博客网 时间:2024/06/14 01:10

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?

阅读全文
0 0