python - 如何延迟生成和处理生成器的结果组合?

标签 python combinations

我有一个生成器,我想对其执行嵌套循环,以便内部循环将从外部循环当前所在的位置开始。 例如,我有一个生成列表 [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/

相关文章:

c++ - boost::python: 编译失败,因为复制构造函数是私有(private)的

javascript - 创建一个由所有唯一的 4 位数字组成的数组,这些数字可以由 JavaScript 中的数字 1-9 组成

python - 如何直接从命令行登录应用程序,即通过在 Pytest 的命令行中提供 URL、用户名、密码

python - 展平 pandas DataFrame

python - 新手 python - 在数组中替换

python - 导出为 PDF 时如何避免使用 matplotlib 调整图形大小?

python - 求和 : Is recursion necessary, 以及递归算法是什么样的?

c# - 在 C# 中对 n 个列表的所有列表项选项进行操作

c# - 从集合中获取不同的组合

r - 添加条件以在 R 中扩展网格?