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

标签 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

最佳答案

itertools.product 就是您要寻找的。它需要多个 Iterable(列表是可迭代的)并生成一个生成器,循环遍历每个 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)

关于python - n 个列表中项目的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56134606/

相关文章:

python - pytesseract 错误 Windows 错误 [错误 2]

python - Pyglet: 'str'对象没有属性 'audio_format'(python)

python - 如何有效地将 boolean numpy 数组转换为阈值 boolean 数组?

arrays - 如何创建名称来自循环的变量

python - 仅比较三重中三个项目中的两个的一部分

c# - Entity Framework 核心 ForEachAsync

Python BeautifulSoup 搜索

python - Pycharm: "No Python interpreter configured for the project"每次

javascript - Parse.com 循环内查询

java - 如何迭代 Future<List> 对象?