在 Python 生成器中反转 next()
reverse next() in Python generator
假设我们有以下代码:
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)
.
,当前实现使迭代跳过数字
您可以使用 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
假设我们有以下代码:
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)
.
您可以使用 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