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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16814984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:43:58  来源:igfitidea点击:

Python list iterator behavior and next(iterator)

pythonlistiteratoriteration

提问by lvc

Consider:

考虑:

>>> 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)

to skip every second element: the call to nextshould 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.

跳过每个第二个元素:调用next应该将迭代器推进一次,然后由循环进行的隐式调用应该将其推进第二次——并且第二次调用的结果将被分配给i

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

它没有。循环打印列表中的所有项目,不跳过任何项目。

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

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

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

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

采纳答案by Martijn Pieters

What you see is the interpreterechoing back the return value of next()in addition to ibeing printed each iteration:

您看到的是解释器回显的返回值next()除了i每次迭代打印外:

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

So 0is the output of print(i), 1the 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.

所以0是的输出print(i)1从返回值next(),通过交互式解释回荡,等,有仅5次迭代,产生2行每次迭代被写入到所述终端。

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

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

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

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

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

>>> 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

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.

换句话说,next()按预期工作,但因为它从迭代器返回下一个值,由交互式解释器回应,你会相信循环以某种方式有它自己的迭代器副本。

回答by Inbar Rose

Something is wrong with your Python/Computer.

您的 Python/计算机有问题。

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

>>> 
0
2
4
6
8

Works like expected.

像预期的那样工作。

Tested in Python 2.7 and in Python 3+ . Works properly in both

在 Python 2.7 和 Python 3+ 中测试。在两者中都能正常工作

回答by njzk2

What is happening is that next(a)returns the next value of a, which is printed to the console because it is not affected.

发生的事情是next(a)返回 a 的下一个值,该值被打印到控制台,因为它不受影响。

What you can do is affect a variable with this value:

您可以做的是影响具有此值的变量:

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

回答by klm

I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.

我觉得现有的答案有点令人困惑,因为他们只间接地表明了代码示例基本神秘的事:*“打印我”和“未来(一)”是导致他们的结果进行打印。

Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.

由于它们正在打印原始序列的交替元素,并且出乎意料的是“next(a)”语句正在打印,因此看起来好像“print i”语句正在打印所有值。

In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.

从这个角度来看,将“next(a)”的结果分配给一个变量会抑制打印其结果,因此只会打印“i”循环变量的替代值。同样,让“打印”语句发出一些更独特的东西也可以消除它的歧义。

(One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)

(现有答案之一反驳了其他答案,因为该答案将示例代码评估为块,因此解释器不会报告“next(a)”的中间值。)

The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...

一般来说,回答问题的迷人之处在于,一旦你知道答案,就明确地说明显而易见的事情。它可能难以捉摸。一旦你理解了答案,同样地批评答案。这真有趣...

回答by burmer

It behaves the way you want if called as a function:

如果作为函数调用,它会按照您想要的方式运行:

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

回答by Wesley

For those who still do not understand.

对于那些仍然不明白的人。

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

As others have already said, nextincreases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.

正如其他人已经说过的那样,next按预期将迭代器增加 1。将它的返回值赋给一个变量并不会神奇地改变它的行为。