[英]all combination in list of lists without duplicates in python
假设我有一个列表列表
[[a1, a2, a3], [b1, b2], [c1, c2, c3, c4]]
列表中的列表数量是事先不知道的。
我想拥有来自不同列表的所有元素组合,所以
[a1, b1, c1], [a1, b1, c2], ..., [a3, b2, c4]
但如果不同列表中有共同元素,则需要删除所有这些组合。 因此,例如,如果a1 = c2
,则需要在结果列表中删除[a1, b1, c2], [a1, b2, c2]
组合。
要获得所有可能的组合,您可以使用All possible permutations of a set of a lists in Python上的答案,但是您可以自动删除所有具有共同元素的组合吗?
您正在寻找列表的笛卡尔积。 使用itertools.product()
,并过滤元素以确保没有一个是相等的:
from itertools import product
for combo in product(*input_lists):
if len(set(combo)) != len(combo): # not all values unique
continue
print(*combo)
我假设a1 = c2
你的意思是组合中的所有值都必须是唯一的,上面通过从组合创建一个集合来对此进行测试。 如果设置长度小于组合长度,则您有重复值。
您可以将此过滤器放入生成器函数中:
def unique_product(*l, repeat=None):
for combo in product(*l, repeat=repeat):
if len(set(combo)) == len(combo): # all values unique
yield combo
然后for unique in unique_product(*input_lists):
您也可以使用filter()
函数来实现相同的目的,但这会为生成的每个组合调用一个函数。
正如其他人所说,您可以使用 itertools 但您可能需要删除重复项:
import itertools
L = [1,2,3,4]
combos = list(itertools.combinations(L, 2))
pairs = [[x, y] for x in combos for y in combos if not set(x).intersection(set(y))]
list(set(sum(pairs, [])))
然后你将得到这个作为输出:
[(1, 2), (1, 3), (1, 4), (2, 3), (3, 4), (2, 4)]
[编辑]
灵感来自此处提供的答案: https ://stackoverflow.com/a/42924469/8357763
1) itertools.product
all_combinations = itertools.product(elements)
2)用lambda filter
filtered_combinations = filter(lambda x: len(x) != len(set(x)), all_combinations)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.