简体   繁体   English

Python - 没有重复的列表列表的所有组合

[英]Python - All combination of list of lists without duplicates

I would like do a combination of list of lists of string without duplicate of strings inside a combination result but I don't find how to do this.我想在组合结果中组合字符串列表列表而不重复字符串,但我不知道如何做到这一点。

For example:例如:

# Input
pickup_list = [["a", "b", "c"], ["d", "e"], ["a", "c", "f"]]
print(combinaison_function(pickup_list))

# Output
> [["a", "d", "c"], ["a", "d", "f"], ["a", "e", "c"], ["a", "e", "f"], ["b", "d", "a"], ["b", "d", "c"], ...]

In the exemple ["a", "d", ”a"] isn't returned because "a" is a duplicate and that I want to do.在示例中 ["a", "d", "a"] 没有返回,因为 "a" 是重复的并且我想做。

I guess the solution will be with an itertools function but I don't find how to do.我想解决方案将使用 itertools function 但我不知道该怎么做。

Thanx for your replies in advance.感谢您提前回复。

This can be done with itertools.product() then filtering duplicates.这可以通过itertools.product()然后过滤重复来完成。 A quick way to check for duplicates is casting to a set .检查重复项的一种快速方法是强制转换为set

comb_list = []
for comb in itertools.product(*pickup_list):
    if len(set(comb))==len(comb):
        comb_list.append(comb)

with your pickup_list I get:使用您的pickup_list ,我得到:

[('a', 'd', 'c'), ('a', 'd', 'f'), ('a', 'e', 'c'), ('a', 'e', 'f'), ('b', 'd', 'a'), ('b', 'd', 'c'), ('b', 'd', 'f'), ('b', 'e', 'a'), ('b', 'e', 'c'), ('b', 'e', 'f'), ('c', 'd', 'a'), ('c', 'd', 'f'), ('c', 'e', 'a'), ('c', 'e', 'f')]

You could make your own recursive generator:您可以制作自己的递归生成器:

def uCombo(L,used=None):
    if used is None: used = set()   # track used values
    if not L: yield [];return       # end of recursion
    for n in L[0]:                  # combine each unused value
        if n in used: continue      # with remaining sub-lists
        yield from ( [n]+c for c in uCombo(L[1:],used | {n}) )
    

output: output:

pickup_list = [["a", "b", "c"], ["d", "e"], ["a", "c", "f"]]
for combo in uCombo(pickup_list): print(combo)
                     
['a', 'd', 'c']
['a', 'd', 'f']
['a', 'e', 'c']
['a', 'e', 'f']
['b', 'd', 'a']
['b', 'd', 'c']
['b', 'd', 'f']
['b', 'e', 'a']
['b', 'e', 'c']
['b', 'e', 'f']
['c', 'd', 'a']
['c', 'd', 'f']
['c', 'e', 'a']
['c', 'e', 'f']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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