了解Python中的for循环迭代器

2024-06-16 10:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我正在努力确保我正确理解python中的for循环。你知道吗

for i in range(1,10):
    print i

我知道range(1,10)将返回一个iterable列表,for循环将调用listsiter()函数,该函数将返回一个迭代器。但我的问题是“我”这个词。for循环调用其iter()函数生成的列表范围(1,10)返回的迭代器是否存储在“i”中,循环最终将在i上运行next()函数来遍历列表?你知道吗


Tags: 函数in列表forrangeiterablenextprint
2条回答
for i in range(1,10):
    print(i)

相当于

_iterator = iter(range(1, 10))
while True:
    try:
        i = next(_iterator)
    except StopIteration:
        break
    print(i)

也就是说,在每次迭代开始时,迭代器产生的下一个值被分配给循环变量。你知道吗

Understanding Python's "for" statement

And in its simplest and original form, this is exactly what the for-in statement does; when you write

for name in train:
    do something with name

the interpreter will simply fetch train[0]and assign it to name, and then execute the code block. It’ll then fetch train[1], train[2], and so on, until it gets an IndexError.


或者,我们可以使用^{}并检查机器代码:

>>> def forloop():
    for i in range(1, 10):
        print i
>>> dis.dis(forloop)
  2           0 SETUP_LOOP              28 (to 31)
              3 LOAD_GLOBAL              0 (range)
              6 LOAD_CONST               1 (1)
              9 LOAD_CONST               2 (10)
             12 CALL_FUNCTION            2
             15 GET_ITER            
        >>   16 FOR_ITER                11 (to 30)
             19 STORE_FAST               0 (i)

  3          22 LOAD_FAST                0 (i)
             25 PRINT_ITEM          
             26 PRINT_NEWLINE       
             27 JUMP_ABSOLUTE           16
        >>   30 POP_BLOCK           
        >>   31 LOAD_CONST               0 (None)
             34 RETURN_VALUE        

我们设置一个循环,呼叫范围,然后:

16^{}11 (to 30)

它将迭代器的结果推送到堆栈上,然后我们将其STORE_FAST作为i使用。你知道吗

当迭代器完成时,FOR_ITERTOS弹出[迭代器],字节码计数器按增量递增。dis显示的是30:POP_BLOCK,结束for循环。你知道吗

这与开头描述的过程一致。你知道吗

相关问题 更多 >