我想知道删除 Python 中执行的迭代器的域空间是否安全(记录的行为?)。
考虑代码:
import os
import sys
sampleSpace = [ x*x for x in range( 7 ) ]
print sampleSpace
for dx in sampleSpace:
print str( dx )
if dx == 1:
del sampleSpace[ 1 ]
del sampleSpace[ 3 ]
elif dx == 25:
del sampleSpace[ -1 ]
print sampleSpace
“sampleSpace”就是我所说的“迭代器的域空间”(如果有更合适的单词/短语,请让我知道)。
我正在做的是在迭代器“dx”运行时从中删除值。
这是我对代码的期望:
Iteration versus element being pointed to (*):
0: [*0, 1, 4, 9, 16, 25, 36]
1: [0, *1, 4, 9, 16, 25, 36] ( delete 2nd and 5th element after this iteration )
2: [0, 4, *9, 25, 36]
3: [0, 4, 9, *25, 36] ( delete -1th element after this iteration )
4: [0, 4, 9, 25*] ( as the iterator points to nothing/end of list, the loop terminates )
..这是我得到的:
[0, 1, 4, 9, 16, 25, 36]
0
1
9
25
[0, 4, 9, 25]
正如你所看到的 - 我所期望的就是我得到的 -which与我在这种情况下从其他语言得到的行为相反。
因此 - 我想问你Python中是否有一些规则,例如“如果在迭代期间改变迭代器的空间,则迭代器将变得无效”?
在Python中做这样的事情安全吗(记录的行为?)?