Python 列表迭代器行为和 next(iterator)

2022-01-10 00:00:00 python list iteration iterator

问题描述

考虑:

>>> lst = iter([1,2,3])
>>> next(lst)
1
>>> next(lst)
2

因此,正如预期的那样,推进迭代器是通过改变同一个对象来处理的.

So, advancing the iterator is, as expected, handled by mutating that same object.

既然如此,我希望:

a = iter(list(range(10)))
for i in a:
   print(i)
   next(a)

每隔一个元素跳过一次:对 next 的调用应该将迭代器推进一次,然后循环进行的隐式调用应该将它第二次推进 - 第二次调用的结果将是分配给 i.

to skip every second element: the call to next should advance the iterator once, then the implicit call made by the loop should advance it a second time - and the result of this second call would be assigned to i.

它没有.循环打印列表中的 all 项,而不跳过任何项.

It doesn't. The loop prints all of the items in the list, without skipping any.

我的第一个想法是这可能会发生,因为循环调用 iter 对它传递的内容,这可能会给出一个独立的迭代器 - 情况并非如此,因为我们有 iter(a) 是一个.

My first thought was that this might happen because the loop calls iter on what it is passed, and this might give an independent iterator - this isn't the case, as we have iter(a) is a.

那么,为什么在这种情况下 next 似乎没有推进迭代器?

So, why does next not appear to advance the iterator in this case?


解决方案

你看到的是interpreter回显next()的返回值除了<每次迭代都会打印代码>i:

What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0
1
2
3
4
5
6
7
8
9

所以0print(i)的输出,1next()的返回值,由交互式解释器等响应.只有 5 次迭代,每次迭代导致 2 行被写入终端.

So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.

如果您分配 next() 的输出,事情会按预期工作:

If you assign the output of next() things work as expected:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    _ = next(a)
... 
0
2
4
6
8

或打印额外信息以区分print()输出与交互式解释器回显:

or print extra information to differentiate the print() output from the interactive interpreter echo:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print('Printing: {}'.format(i))
...    next(a)
... 
Printing: 0
1
Printing: 2
3
Printing: 4
5
Printing: 6
7
Printing: 8
9

换句话说,next() 正在按预期工作,但是由于它从迭代器返回下一个值,并由交互式解释器回显,因此您会相信循环有自己的迭代器以某种方式复制.

In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.

相关文章