如何遍历 n 维列表并找到所有组合

How to loop through an n-dimensional list and find all combinations

我写了一个程序来一起掷骰子。它的工作方式是我将要掷的骰子传递给主函数,[4, 6] 又名 4 面骰子和 6 面骰子。 该程序然后生成 2 个列表,其中单独包含骰子的所有可能结果

[1, 2, 3, 4, 5, 6] and [1, 2, 3, 4]

然后,我列出了所有可能的结果,并添加了两个列表之间的所有数据组合。这是我的代码

#list of outcomes from current dice rolling - to contain sublists within it for each dice
rawDiceOutcomes = []

#list of total outcomes to find probabilities in
finalOutcomes = []

#generate n lists of outcomes 
for i in range(len(dice)):
    rawDiceOutcomes.append([i for i in range(1, dice[i]+1)])    #[1, 2, 3, 4], [1, 2, 3, 4, 5, 6] etc


#TODO : Figure out some way to do this for an n-dimensional list
for x in rawDiceOutcomes[0]:   
    for y in rawDiceOutcomes[1]:
        tempOutcome = x + y
        finalOutcomes.append(tempOutcome)

如评论所示,如果只掷 2 个骰子,我知道该怎么做,但最终,我希望能够掷 3、4、100 个骰子等。我将如何遍历所有列表以便我可以传递任意数量的骰子并且有效吗?

使用itertools.product为任意数量的列表生成任意组合:

import itertools

rawDiceOutcomes = [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4]]
res = [sum(comb) for comb in itertools.product(*rawDiceOutcomes)]
print(res)

输出

[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 7, 8, 9, 10]

以上代码对于rawDiceOutcomes的任何长度都保持不变。

对于任何骰子的一般方法:

from itertools import product

dice = [4, 6]

individual_outcomes = [range(1, d+1) for d in dice]

combined_outcomes = [*map(sum, product(*individual_outcomes))]