假设我们有以下代码:
gen = (x for x in range(11))
for el in gen:
print("Printing current element: ", el) #1
if el % 3 == 0:
print("The next item is: ", next(gen)) #2
在此示例中,我想在行#1
中打印来自生成器的所有数字,并在行#2
中打印3的整数。代码必须使用逐元素(而不是索引)迭代。还存在一个限制,即生成器gen
必须保留为生成器(由于内存限制),并且不能使用,例如作为reversed(list(gen))
中的列表。
当前的实现会由于next(gen)
而使迭代跳过数字。
答案 0 :(得分:2)
您可以使用itertools.tee
复制可迭代对象,并通过调用next
将复制的可迭代对象偏移1,然后使用itertools.zip_longest
将两个可迭代对象配对以进行迭代:
from itertools import tee, zip_longest
gen = (x for x in range(11))
a, b = tee(gen)
next(b)
for el, n in zip_longest(a, b):
print("Printing current element: ", el)
if el % 3 == 0:
print("The next item is: ", n)
这将输出:
Printing current element: 0
The next item is: 1
Printing current element: 1
Printing current element: 2
Printing current element: 3
The next item is: 4
Printing current element: 4
Printing current element: 5
Printing current element: 6
The next item is: 7
Printing current element: 7
Printing current element: 8
Printing current element: 9
The next item is: 10
Printing current element: 10