gpt4 book ai didi

python - python中相同生成器的链式重复

转载 作者:行者123 更新时间:2023-11-28 21:09:51 25 4
gpt4 key购买 nike

考虑以下简单的生成器:

def simple_gen():
for number in range(5):
yield number ** 2

我愿意使用 itertools.repeatitertools.chain 将生成器链接到自身 n 次。为清楚起见,请考虑以下相同的(非生成器)示例:

array = [1,2,3,4]
repetitions = itertools.repeat( array ,2)
list(itertools.chain.from_iterable(repetitions)) -> [1,2,3,4,1,2,3,4]

我想要相同的但使用我自己的生成器 (simple_gen) 而不是数组。当然,简单的替换是行不通的,因为 itertools.repeat 重复相同的对象,因此生成器的后续重复将被耗尽。

关于如何使用 itertools 模块实现此目的的一些想法?

我不想将生成器转换为列表或其他容器。

最佳答案

您可以先将生成器输出转换为列表:

repeat(list(simple_gen()), 2)

否则您不能重复生成器输出。您最多可以重新创建生成器count 次:

from itertools import repeat

def recreate(callable, count=None):
for c in repeat(callable, count):
yield from c()

在 Python 3 和

from itertools import repeat

def recreate(callable, count=None):
for c in repeat(callable, count):
for val in c():
yield val

对于 Python 2 并使用它代替 chain.from_iterable(repeat(callable(), count))。请注意,生成器函数未被调用,而是传入函数对象本身。

演示:

>>> from itertools import repeat
>>> def simple_gen():
... for number in range(5):
... yield number ** 2
...
>>> def recreate(callable, count=None):
... for c in repeat(callable, count):
... for val in c():
... yield val
...
>>> list(recreate(simple_gen, 2))
[0, 1, 4, 9, 16, 0, 1, 4, 9, 16]

关于python - python中相同生成器的链式重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37488346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com