Python中list的遍歷 原

在python中,若要遍歷一個list而且需要在遍歷時修改list,則需要十分注意,因爲這樣可能會導致死循環,例如:

In [10]: ls = ['hello', 'world', 'bugggggggg']

In [11]: for item in ls:
   ....:     if len(item) > 5:
   ....:         ls.insert(0, item)
   ....:         print ls
   ....:         
['bugggggggg', 'hello', 'world', 'bugggggggg']
['bugggggggg', 'bugggggggg', 'hello', 'world', 'bugggggggg']
['bugggggggg', 'bugggggggg', 'bugggggggg', 'hello', 'world', 'bugggggggg']
...

所以,爲了安全起見,在遇到需要修改列表的時候,都不對列表本身進行遍歷,而是創建一個列表的備份,然後對這個備份進行遍歷,從而避免了上述情形。例如:

In [20]: In [10]: ls = ['hello', 'world', 'bugggggggg']

In [21]: for item in ls[:]:
   ....:     if len(item) > 5:
   ....:         ls.insert(0, item)
   ....:         

In [22]: print(ls)
['bugggggggg', 'hello', 'world', 'bugggggggg']

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章