問(wèn)題描述
以下代碼:
a = list(range(10))
remove = False
for b in a:
if remove:
a.remove(b)
remove = not remove
print(a)
使用 Python 時(shí)輸出 [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.
- 為什么會(huì)輸出這些特定的值?
- 為什么沒(méi)有錯(cuò)誤提示底層迭代器正在被修改?
- 在這種行為方面,與早期版本的 Python 相比,機(jī)制是否發(fā)生了變化?
請(qǐng)注意,我并不是要解決這種行為,而是要理解它.
Note that I am not looking to work around the behaviour, but to understand it.
推薦答案
我爭(zhēng)論了一段時(shí)間來(lái)回答這個(gè)問(wèn)題,因?yàn)轭愃频膯?wèn)題在這里已經(jīng)被問(wèn)過(guò)很多次了.但它的獨(dú)特性足以讓人們從懷疑中受益.(不過(guò),如果其他人投票結(jié)束,我不會(huì)反對(duì).)這是對(duì)正在發(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
^
由于沒(méi)有其他人有,我將嘗試回答您的其他問(wèn)題:
Since no one else has, I'll attempt to answer your other questions:
為什么沒(méi)有給出錯(cuò)誤指示底層迭代器正在被修改?
Why is no error given to indicate that underlying iterator is being modified?
要在不禁止許多完全有效的循環(huán)構(gòu)造的情況下拋出錯(cuò)誤,Python 必須很多了解正在發(fā)生的事情,并且它可能必須在運(yùn)行時(shí)獲取該信息.所有這些信息都需要時(shí)間來(lái)處理.它會(huì)讓 Python 慢很多,只是在速度真正重要的地方——一個(gè)循環(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 相比,機(jī)制是否發(fā)生了變化?
Have the mechanics changed from earlier versions of Python with respect to this behaviour?
簡(jiǎn)而言之,沒(méi)有.或者至少我高度對(duì)此表示懷疑,而且自從我學(xué)習(xí) Python (2.4) 以來(lái)它的表現(xiàn)肯定是這樣的.坦率地說(shuō),我希望可變序列的任何直接實(shí)現(xiàn)都以這種方式運(yùn)行.哪位知道的好,請(qǐng)指正.(實(shí)際上,快速文檔查找確認(rè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)于在迭代列表時(shí)從列表中刪除的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!