Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用itertools从一组可变列表中获得的总组合_Python_List_Itertools - Fatal编程技术网

Python 使用itertools从一组可变列表中获得的总组合

Python 使用itertools从一组可变列表中获得的总组合,python,list,itertools,Python,List,Itertools,我正在使用python,我相信下面的问题可以通过itertools解决,但是如果有其他方法,请告诉我 如果我有一个变量列表集(为了便于说明,让它为3),并且每个列表包含一个变量元素集(元素可以是字符串、整数、列表) 例如: [a,b,c] [d,e,f] [g,h,i] 如何创建(并访问)所有可能的组合(最好是列表),从每组中选择一个 i、 e [a、d、g] [a、d、h] [a,d,i] [a,e,g] 。。。(等等) 顺序并不重

我正在使用python,我相信下面的问题可以通过itertools解决,但是如果有其他方法,请告诉我

如果我有一个变量列表集(为了便于说明,让它为3),并且每个列表包含一个变量元素集(元素可以是字符串、整数、列表)

例如:

                          [a,b,c]   [d,e,f]   [g,h,i]
如何创建(并访问)所有可能的组合(最好是列表),从每组中选择一个

i、 e

[a、d、g]

[a、d、h]

[a,d,i]

[a,e,g]

。。。(等等)

顺序并不重要,所以对于输出,我不希望[a,d,g]和[d,a,g]都显示,只是[a,d,g]

如果我的问题不清楚,请告诉我


此外,如果它有帮助,我们可以考虑所有元素都是简单的字符串或整数,但是我想要一个解决方案,考虑到列表中的列表个数和每个列表中元素的数量是可变的。p> 我无法将其标记为重复,但我认为您需要

itertools.product
,如下所述:

您可以使用深度优先搜索解决此问题:

def find_all_combinations(lists):
    res = set() #set so no duplicates
    def dfs(curr_index, curr_combination):
        if curr_index == len(lists): #base case - add to results and stop
            res.add(tuple(sorted(curr_combination)))
        else:
            for i in lists[curr_index]: #iterate through each val in cur index
                dfs(curr_index + 1, curr_combination + [i]) #add and repeat for next index
    dfs(0, [])
    return sorted(list(res))

print(find_all_combinations(l))
>>>[('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'), ('a', 'f', 'g'), ('a', 'f', 'h'), ('a', 'f', 'i'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i'), ('b', 'f', 'g'), ('b', 'f', 'h'), ('b', 'f', 'i'), ('c', 'd', 'g'), ('c', 'd', 'h'), ('c', 'd', 'i'), ('c', 'e', 'g'), ('c', 'e', 'h'), ('c', 'e', 'i'), ('c', 'f', 'g'), ('c', 'f', 'h'), ('c', 'f', 'i')]
另外一个好处是,您的所有列表不必具有相同的长度