python : dictionary changed size during iteration

1. 错误方式

#这里初始化一个dict
>>> d = {'a':1, 'b':0, 'c':1, 'd':0}
#本意是遍历dict,发现元素的值是0的话,就删掉
>>> for k in d:
...   if d[k] == 0:
...     del(d[k])
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
#结果抛出异常了,两个0的元素,也只删掉一个。
>>> d
{'a': 1, 'c': 1, 'd': 0}

>>> d = {'a':1, 'b':0, 'c':1, 'd':0}
#d.keys() 是一个下标的数组
>>> d.keys()
['a', 'c', 'b', 'd']
#这样遍历,就没问题了,因为其实其实这里遍历的是d.keys()这个list常量。
>>> for k in d.keys():
...   if d[k] == 0:
...     del(d[k])
...
>>> d
{'a': 1, 'c': 1}
#结果也是对的
>>>

2.正确方式

>>> a = [1,2,0,3,0,4,5]
>>> a = [i for i in alist if i != 0]
>>> a
[1, 2, 3, 4, 5]

>>> d = {'a':1, 'b':0, 'c':1, 'd':0} >>> d = {k:v for k,v in d.iteritems() if v !=0 } >>> d {'a':1,'c':1'}
原文地址:https://www.cnblogs.com/yuyutianxia/p/5106386.html