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'}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM