删除执行中迭代器的域是否安全(记录的行为?)

2024-01-15

我想知道删除 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中做这样的事情安全吗(记录的行为?)?


From Python 教程 http://docs.python.org/tutorial/controlflow.html#for-statements:

修改序列不安全 在循环中迭代(这 只能发生在可变序列上 类型,例如列表)。如果你需要 修改您正在迭代的列表 (例如,要复制选定的 items)你必须迭代一个副本。 切片符号使得这个 特别方便:

>>> for x in a[:]: # make a slice copy of the entire list
...    if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

删除执行中迭代器的域是否安全(记录的行为?) 的相关文章

随机推荐