Python itertools产品函数列表中一次两个元素
我有以下清单:Python itertools产品函数列表中一次两个元素,python,python-3.x,combinations,itertools,cartesian-product,Python,Python 3.x,Combinations,Itertools,Cartesian Product,我有以下清单: 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,
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)))))
这在本手册中有介绍。使用参数
repeat=2
列表(组合\u与替换(L,2))
?@Prune,它给我的组合是(0,0),(0,25),(0,50)…
等。我想要的结果就像我提到的那样,每对重复组合。@deadshot也没有给我每对重复组合。还有什么我可以试试的吗?list(组合_与替换(L,2))+list(组合_与替换(L[:-1],2))
?你(几乎)不需要将你迭代的东西包装在list
构造函数中(罕见的例外是当你对你迭代的东西进行变异时,这里不是这样)<代码>用于其中的c。组合(L,2):可以在不浪费时间的情况下创建一个临时的列表。是的,你说得对,谢谢