python - n 个列表中项目的所有可能组合
问题描述
我需要开发一个列表,其中包含 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.product
就是你要找的。它需要多个Iterable
s(列表是可迭代的)并生成一个生成器,该生成器循环遍历它们中的每一个的所有组合。
参见示例:
>>> 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)
推荐阅读
- maven - 自定义插件的源代码中是否指定了目标?
- python - 如何在同一格式规范中一个接一个地添加一个字符/字符串
- python - 多输出回归器和 sklearn 的 RFE 模块
- python - 找不到 Statsmodel.varmax 应用或附加
- javascript - 如何从一个公共方法中提取变量的值并调用另一种方法
- powershell - 需要根据成本管理 API 查找资源组支出的总计
- makefile - 编写通用 make 目标时,如何仅使用两个目录之一中的文件?
- android - Android Q Camera 2 权限崩溃应用
- python - 计算数据子集每列的 n 个值的平均值的问题
- javascript - 在 Firestore 云函数中,forEach 循环返回数据库中项目数的倍数