gpt4 book ai didi

python - 我如何懒惰地生成和处理来自生成器的结果组合?

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:01 24 4
gpt4 key购买 nike

我有一个生成器,我想对其执行嵌套循环,使内循环将从外循环所在的位置开始。例如,我有一个生成列表 [1,2,3] 的生成器,我的循环应该生成:(1,2),(1,3),(2, 3)。我想出的代码如下:

from itertools import tee

def my_gen():
my_list = [1, 2, 3]
for x in my_list:
yield x

first_it = my_gen()
while True:
try:
a = next(first_it)
first_it, second_it = tee(first_it)
for b in second_it:
print(a,b)
except StopIteration:
break

这段代码很麻烦,效率不高,而且在我看来也不是很 pythonic。请注意,我不能使用 combinations_with_replacement,因为我需要一个内部循环来处理来自外部循环的特定值。

对于更优雅和 pythonic 的代码有什么建议吗?

最佳答案

重复克隆和耗尽其中一个生成的迭代器效率不高。根据 itertools.tee docs :

In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

from itertools import islice

my_list = [1, 2, 3]
# or, more generally
# my_list = list(my_gen())

for i, a in enumerate(my_list):
for b in islice(my_list, i+1, None):
print((a, b))
(1, 2)
(1, 3)
(2, 3)

关于python - 我如何懒惰地生成和处理来自生成器的结果组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47977449/

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