問題描述
以下代碼:
a = list(range(10))
remove = False
for b in a:
if remove:
a.remove(b)
remove = not remove
print(a)
使用 Python 時輸出 [0, 2, 3, 5, 6, 8, 9]
,而不是 [0, 2, 4, 6, 8]
3.2.
Outputs [0, 2, 3, 5, 6, 8, 9]
, instead of [0, 2, 4, 6, 8]
when using Python 3.2.
- 為什么會輸出這些特定的值?
- 為什么沒有錯誤提示底層迭代器正在被修改?
- 在這種行為方面,與早期版本的 Python 相比,機制是否發(fā)生了變化?
請注意,我并不是要解決這種行為,而是要理解它.
Note that I am not looking to work around the behaviour, but to understand it.
推薦答案
我爭論了一段時間來回答這個問題,因為類似的問題在這里已經(jīng)被問過很多次了.但它的獨特性足以讓人們從懷疑中受益.(不過,如果其他人投票結(jié)束,我不會反對.)這是對正在發(fā)生的事情的直觀解釋.
I debated answering this for a while, because similar questions have been asked many times here. But it's just unique enough to be given the benefit of the doubt. (Still, I won't object if others vote to close.) Here's a visual explanation of what is happening.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <- b = 0; remove? no
^
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <- b = 1; remove? yes
^
[0, 2, 3, 4, 5, 6, 7, 8, 9] <- b = 3; remove? no
^
[0, 2, 3, 4, 5, 6, 7, 8, 9] <- b = 4; remove? yes
^
[0, 2, 3, 5, 6, 7, 8, 9] <- b = 6; remove? no
^
[0, 2, 3, 5, 6, 7, 8, 9] <- b = 7; remove? yes
^
[0, 2, 3, 5, 6, 8, 9] <- b = 9; remove? no
^
由于沒有其他人有,我將嘗試回答您的其他問題:
Since no one else has, I'll attempt to answer your other questions:
為什么沒有給出錯誤指示底層迭代器正在被修改?
Why is no error given to indicate that underlying iterator is being modified?
要在不禁止許多完全有效的循環(huán)構(gòu)造的情況下拋出錯誤,Python 必須很多了解正在發(fā)生的事情,并且它可能必須在運行時獲取該信息.所有這些信息都需要時間來處理.它會讓 Python 慢很多,只是在速度真正重要的地方——一個循環(huán).
To throw an error without prohibiting many perfectly valid loop constructions, Python would have to know a lot about what's going on, and it would probably have to get that information at runtime. All that information would take time to process. It would make Python a lot slower, in just the place where speed really counts -- a loop.
在這種行為方面,與早期版本的 Python 相比,機制是否發(fā)生了變化?
Have the mechanics changed from earlier versions of Python with respect to this behaviour?
簡而言之,沒有.或者至少我高度對此表示懷疑,而且自從我學習 Python (2.4) 以來它的表現(xiàn)肯定是這樣的.坦率地說,我希望可變序列的任何直接實現(xiàn)都以這種方式運行.哪位知道的好,請指正.(實際上,快速文檔查找確認 從 version 1.4!)
In short, no. Or at least I highly doubt it, and certainly it has behaved this way since I learned Python (2.4). Frankly I would expect any straightforward implementation of a mutable sequence to behave in just this way. Anyone who knows better, please correct me. (Actually, a quick doc lookup confirms that the text that Mikola cited has been in the tutorial since version 1.4!)
這篇關(guān)于在迭代列表時從列表中刪除的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!