【发布时间】:2019-05-15 00:35:33
【问题描述】:
我需要开发一个列表,其中包含 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
【问题讨论】:
-
看看
itertools.combinations()。 -
您可以为您的
chords添加预期的输出吗?有点混乱。 -
嗯,基本上是这样的:和弦看起来像 [1, 4, 8, 12](它们是四个音符)。然后有一个列表,其中包含同一基础的所有可能注释。之后,所有具有不同基数的不同和弦都在同一个列表中,列表和弦。
-
恭喜您提出第一个问题并接受答案!如果您有其他问题,请不要忘记返回 Stack Overflow。