列表列表中的所有组合,在python

时间:2018-03-11 11:27:02

标签: 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 lists in Python上的答案,但是您可以自动删除所有具有共同元素的组合吗?

3 个答案:

答案 0 :(得分:2)

您正在寻找列表的Cartesian Product。使用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() function来实现相同的功能,但会为每个组合产生一个函数调用。

答案 1 :(得分:1)

1)itertools.product

 all_combinations = itertools.product(elements)

2)filter与lambda

filtered_combinations = filter(lambda x: len(x) != len(set(x)), all_combinations)

答案 2 :(得分:1)

正如其他人所说,您可以使用 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