简体   繁体   中英

all combination in list of lists without duplicates in python

let say I have a list of lists

[[a1, a2, a3], [b1, b2], [c1, c2, c3, c4]]

The number of lists in the list is not known in advance.

I want to have all combinations of elements from the different list, so

[a1, b1, c1], [a1, b1, c2], ..., [a3, b2, c4] 

but if there common elements in the different list, all these combinations need to be deleted. So if for example, a1 = c2 , then the combinations [a1, b1, c2], [a1, b2, c2] need to be deleted in the resulting list.

To get all possible combinations, you can use the answer on All possible permutations of a set of lists in Python , but can you automaticaly delete all combinations with common elements?

You are looking for the Cartesian Product of your lists. Use itertools.product() , and filter the elements to make sure none are equal:

from itertools import product

for combo in product(*input_lists):
    if len(set(combo)) != len(combo):  # not all values unique
        continue
    print(*combo)

I'm assuming that by a1 = c2 you mean that all values in the combination need to be unique , the above tests for this by creating a set from the combination. If the set length is smaller than the combination length, you had repeated values.

You can put this filter into a generator function:

def unique_product(*l, repeat=None):
    for combo in product(*l, repeat=repeat):
        if len(set(combo)) == len(combo):  # all values unique
            yield combo

then use for unique in unique_product(*input_lists):

You can also use the filter() function to achieve the same, but that incurs a function call for each combination produced.

As the other guys said, you can do with itertools but you may need to drop duplicates:

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, [])))

And then the you will have this as output:

[(1, 2), (1, 3), (1, 4), (2, 3), (3, 4), (2, 4)]

[EDIT]

Inspired on the answer provided here: https://stackoverflow.com/a/42924469/8357763

1) itertools.product

 all_combinations = itertools.product(elements)

2) filter with lambda

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM