Python列表迭代器行为和下一个(迭代器) [英] Python list iterator behavior and next(iterator)

查看:303
本文介绍了Python列表迭代器行为和下一个(迭代器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

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

因此,正如预期的那样,推进迭代器是由改变同一个对象。

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

在这种情况下,我希望:

This being the case, I would expect:

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.

事实并非如此。循环打印列表中所有项目,而不跳过任何项目。

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?

推荐答案

你看到的是解释器回显的返回值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

所以 0 print(i)的输出, 1 来自 next()的返回值,由交互式解释器等回显。只有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

或打印额外用于区分交互式解释器echo的 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.

这篇关于Python列表迭代器行为和下一个(迭代器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆