gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:23:38 25 4
gpt4 key购买 nike

我想知道删除在 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]

如您所见 - 我所期望的就是我得到的 - 与我在这种情况下从其他语言获得的行为相反。

因此 - 我想问你在 Python 中是否有类似“如果你在迭代期间改变它的空间,迭代器变得无效”这样的规则?

在 Python 中做这样的事情安全吗(有记录的行为?)?

最佳答案

来自 the Python tutorial :

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient:

>>> 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']

关于python - 删除执行中的迭代器的域是安全的(记录的行为?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2965351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com