itertools 产品函数在列表中一次两个元素

itertools product function two elements at a time in a list

我有以下列表:

L = [0, 25, 50, 75, 100]

我想查找此列表的所有可能组合,但一次查找两个元素,例如:

Combi = [(0, 0), (0, 25), (25,0), (25, 25), (0, 0), (0, 50), (50, 0), (50, 50), (0, 0), (0, 75), (75, 0), (75, 75)...]

等等。

有什么简洁的方法可以实现吗?

尝试

out=[]
for c in list(it.combinations(L,2)):
  out.extend (it.product(c, repeat=2))

一些使用列表理解的方法:

list = [0, 25, 50, 75, 100]
new_list = [(list[i], j) for i in range(len(list)) for j in list]

给你,如果我没理解错的话:

from itertools import combinations_with_replacement

L = [0, 25, 50, 75, 100]

combi = []
for a,b in combinations_with_replacement(L, 2):
    combi.append((a,b))
    if a != b:
        combi.append((b,a))

给出:

[(0, 0),
 (0, 25),
 (25, 0),
 (0, 50),
 (50, 0),
 (0, 75),
 (75, 0),
 (0, 100),
 (100, 0),
 (25, 25),
 (25, 50),
 (50, 25),
 (25, 75),
 (75, 25),
 (25, 100),
 (100, 25),
 (50, 50),
 (50, 75),
 (75, 50),
 (50, 100),
 (100, 50),
 (75, 75),
 (75, 100),
 (100, 75),
 (100, 100)]

您似乎想要输入中所有唯一对的乘积。您可以将三个 itertools 函数结合在一起来实现此目的:

from itertools import chain, combinations, product

L = [0, 25, 50, 75, 100]

print(list(chain.from_iterable(product(pair, repeat=2) for pair in combinations(L, 2))))

输出符合您的规范:

[(0, 0), (0, 25), (25, 0), (25, 25), (0, 0), (0, 50), (50, 0), (50, 50), (0, 0), (0, 75), (75, 0), (75, 75), (0, 0), (0, 100), (100, 0), (100, 100), (25, 25), (25, 50), (50, 25), (50, 50), (25, 25), (25, 75), (75, 25), (75, 75), (25, 25), (25, 100), (100, 25), (100, 100), (50, 50), (50, 75), (75, 50), (75, 75), (50, 50), (50, 100), (100, 50), (100, 100), (75, 75), (75, 100), (100, 75), (100, 100)]

如果你想把工作全部推到C层(每个组合没有生成器表达式字节代码执行),另一个导入(和一些更密集的代码)可以带你去那里:

from functools import partial

print(list(chain.from_iterable(map(partial(product, repeat=2), combinations(L, 2)))))