我需要开发一个包含所有可能组合的列表,按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.产品():
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
itertools.product
就是你要找的。它需要多个Iterable
(列表是iterables)并生成一个生成器,该生成器对每个列表的所有组合进行循环。你知道吗参见示例:
所以你的用例会变成:
相关问题 更多 >
编程相关推荐