問題描述
考慮:
>>> 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
所以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
或打印額外信息以區分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 列表迭代器行為和 next(iterator)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!