本文介紹了不允許在 Python 中修改列表迭代器?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
簡單示例:
myList = [1, 2, 3, 4, 5]
for obj in myList:
obj += 1
print myList
打印
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
同時:
myList = [1, 2, 3, 4, 5]
for index in range(0,len(myList)):
myList[index] += 1
print myList
打印
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
結論:
- 列表可以使用全局列表訪問來修改列表可以
- 可以不使用迭代器對象修改列表項
- Lists can be modified in place using global list access Lists can
- List items can NOT be modified in place using the iterator object
我能找到的所有示例代碼都使用全局列表訪問器來就地修改列表.修改列表迭代器就這么邪惡嗎?
All example code I can find uses the global list accessors to modify the list inplace. Is it so evil to modify a list iterator?
推薦答案
在 for obj in myList:
中,在每次迭代中,obj
是myList
中的元素.所以對 obj
的更改對 myList
的元素沒有任何影響.
in for obj in myList:
, in every iteration, obj
is a (shallow) copy of the element in myList
. So the change on the obj
does nothing to myList
's elements.
這與 Perl for my $obj (@myList) {}
這篇關于不允許在 Python 中修改列表迭代器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!