gpt4 book ai didi

python - 在遍历迭代器时重新分配迭代器的值

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:12 35 4
gpt4 key购买 nike

First of all a disclaimer:

I don't want to use a code like this, I am aware it is a bad practice. As well I am not interested in tips on how to improve it, to make it right. What interests me is a theory.

为什么这样的代码可以在 python 3.6 中运行:

ls = range(5)
for elem_a in ls:

ls = range(5, 10)
for elem_b in ls:
print(elem_a, elem_b)

我正在重新分配 ls 的值,同时遍历它。第一次执行for elem_a in ls时,第一次迭代中ls的值是否存储在内存中?

最佳答案

重新分配您正在循环的变量没有任何效果,因为变量不会在每次迭代时重新计算。事实上,循环在内部遍历 iterator。 ,不超过您的 range 对象。

基本上如果你有这样的循环:

seq = range(5)
for elem in seq:
seq = something_else

Python 将其重写为如下内容:

seq = range(5)

loop_iter = iter(seq) # obtain an iterator
while True:
try:
elem = next(loop_iter) # get the next element from the iterator
except StopIteration:
break # the iterator is exhausted, end the loop

# execute the loop body
seq = something_else

这个的关键方面是循环有它自己对存储在 loop_iter 中的 iter(seq) 的引用,因此自然地重新分配 seq对循环没有影响。

所有这些都在 compound statement documentation 中进行了解释:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
["else" ":" suite]

The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator.

关于python - 在遍历迭代器时重新分配迭代器的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53115873/

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