n个列表中项目的所有可能组合

时间:2019-05-14 16:12:21

标签: python arrays list

我需要开发一个列表,该列表按n个列表中的元素顺序包含所有可能的组合。基本上,我正在尝试查找所有可能的路径,以后在程序的另一部分将需要它们。

我已经为两个列表编写了一些简单的代码,但是问题是我不知道用户会给出多少输入,所以我不得不猜测。目前,我已经定义了一个输出所有可能组合的函数(仅一种方式,因为它们是路径)。我还一直在测试其他替代方法,例如itertools(我认为可能可以解决我的问题的答案),或使用numpy数组(这样做的问题是我的数组不是同质的)。

输入列表可能看起来像这样(3个维度):

chords = [[[1, 4, 8, 12], [1, 4, 10, 12]], [[4, 7, 13, 19], [4, 9, 13, 21]]]

我的函数可以在两个列表之间生成排列:

def combination(list1, list2):
    list = []
    for x in list1:
        for y in list2:
            list.append([x,y])
    return list

combination(chords[0], chords[1])

此函数按预期工作,但是问题出在例如我介绍combination(combination(chords[0], chords[1]), chords[3])chords[0]时不算在内的chords[1](仍然按预期工作)。

编辑:

好的,就像@iBug指出的那样,一个很好的方法是使用itertools.product():

bases_chords = [···] #It's a three dimensional array I've filled out  before
possibilities = [] #The list that will contain all the different combinations

for a in product(*bases_chords): #The asterisk means that I input everything on the list
    possibilities.append(a)

print(possibilities)
print(len(possibilities)) #Just to check if the dimensions are right

1 个答案:

答案 0 :(得分:1)

itertools.product是您要寻找的。它需要多个Iterable(列表是可迭代的),并生成一个生成器,该生成器循环遍历它们中的每个组合。

查看示例:

>>> for a, b, c in itertools.product([1, 2, 3], "abc", [True, False]):
...  print(a, b, c)
...
1 a True
1 a False
1 b True
1 b False
1 c True
1 c False
2 a True
2 a False
2 b True
2 b False
2 c True
2 c False
3 a True
3 a False
3 b True
3 b False
3 c True
3 c False
>>>

因此您的用例将变成:

itertools.product(*chords)
相关问题