Python for循环是否调用iter?
请看下面的示例:Python for循环是否调用iter?,python,Python,请看下面的示例: a = [1, 2, 3, 4] for i in a: print(a) “a”是列表(iterable),而不是迭代器 我不是想知道iter或iter()将列表转换为迭代器 我想知道for循环本身是否隐式地转换了列表,然后调用iter来进行迭代,而不删除类似迭代器的列表 由于stackoverflow认为我的问题可能重复: uniqe部分,我不是问for loop作为概念,也不是问iter,我是问for loop的核心机制以及与iter的关系 谢谢 我想知道fo
a = [1, 2, 3, 4]
for i in a:
print(a)
“a”是列表(iterable),而不是迭代器
我不是想知道iter或iter()将列表转换为迭代器
我想知道for循环本身是否隐式地转换了列表,然后调用iter来进行迭代,而不删除类似迭代器的列表
由于stackoverflow认为我的问题可能重复:
uniqe部分,我不是问for loop作为概念,也不是问iter,我是问for loop的核心机制以及与iter的关系
谢谢
我想知道for循环本身是否隐式地转换列表,然后调用iter进行迭代,保持列表而不删除,比如迭代器
for
循环不会隐式转换列表,因为它会改变列表,但会从列表隐式创建迭代器。列表本身在迭代期间不会更改状态,但创建的迭代器将更改状态
a = [1, 2, 3]
for x in a:
print(x)
相当于
a = [1, 2, 3]
it = iter(a) # calls a.__iter__
while True:
try:
x = next(it)
except StopIteration:
break
print(x)
下面是\uuuu iter\uuuu
实际被调用的证据:
import random
class DemoIterable(object):
def __iter__(self):
print('__iter__ called')
return DemoIterator()
class DemoIterator(object):
def __iter__(self):
return self
def __next__(self):
print('__next__ called')
r = random.randint(1, 10)
if r == 5:
print('raising StopIteration')
raise StopIteration
return r
可拆卸的上的迭代:
>>> di = DemoIterable()
>>> for x in di:
... print(x)
...
__iter__ called
__next__ called
9
__next__ called
8
__next__ called
10
__next__ called
3
__next__ called
10
__next__ called
raising StopIteration
我不确定我是否理解“我想知道for循环本身是否隐式转换列表,然后调用iter for iteration保留列表,而不删除类似iterator的内容?”你是什么意思?我不明白你的问题,你想知道for循环如何在列表中迭代?@LethalProgrammer是的。如果与国际热核实验堆有任何关联,@anati的可能重复。我不确定你在我的评论中发现了什么不合适的地方。我唯一能想到的就是“dupe”这个词,它是这个网站上“replicate”的通俗说法。