在Python生成器中反转next()

时间:2019-04-02 17:53:17

标签: python for-loop iterator next

假设我们有以下代码:

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)而使迭代跳过数字。

1 个答案:

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