gpt4 book ai didi

python - 在循环期间更改可迭代变量

转载 作者:太空狗 更新时间:2023-10-29 22:08:59 26 4
gpt4 key购买 nike

it 成为 python 中的可迭代元素。在什么情况下会反射(reflect) it 循环中 it 的变化?或者更直截了当:这样的事情什么时候起作用?

it = range(6)
for i in it:
it.remove(i+1)
print i

导致打印 0,2,4(显示循环运行 3 次)。

另一方面是

it = range(6)
for i in it:
it = it[:-2]
print it

导致输出:

[0,1,2,3]
[0,1]
[]
[]
[]
[],

显示循环运行了 6 次。我猜它与就地操作或变量范围有关,但我不能 100% 肯定它。

澄清:

一个例子,那是行不通的:

it = range(6)
for i in it:
it = it.remove(i+1)
print it

导致打印“None”并抛出错误(NoneType 没有属性“remove”)。

最佳答案

当你迭代一个 list 时,你实际上调用了 list.__iter__(),它返回一个绑定(bind)到 listiterator 对象list,然后实际迭代此 listiterator。从技术上讲,这:

itt = [1, 2, 3]
for i in itt:
print i

实际上是一种语法糖:

itt = [1, 2, 3]
iterator = iter(itt)
while True:
try:
i = it.next()
except StopIteration:
break
print i

因此此时 - 在循环内 - 重新绑定(bind) itt 不会影响 listiterator(它保留自己对列表的引用),但是 改变 itt 显然会影响它(因为两个引用都指向同一个列表)。

IOW 它与重新绑定(bind)和变异之间的旧区别相同......如果没有 for 循环,你会得到相同的行为:

# creates a `list` and binds it to name "a"
a = [1, 2, 3]
# get the object bound to name "a" and binds it to name "b" too.
# at this point "a" and "b" both refer to the same `list` instance
b = a
print id(a), id(b)
print a is b
# so if we mutate "a" - actually "mutate the object bound to name 'a'" -
# we can see the effect using any name refering to this object:
a.append(42)
print b

# now we rebind "a" - make it refer to another object
a = ["a", "b", "c"]
# at this point, "b" still refer to the first list, and
# "a" refers to the new ["a", "b", "c"] list
print id(a), id(b)
print a is b
# and of course if we now mutate "a", it won't reflect on "b"
a.pop()
print a
print b

关于python - 在循环期间更改可迭代变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38658490/

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