繁体   English   中英

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

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

我写了一个程序来一起掷骰子。 它的工作方式是我将要掷的骰子传递给主要的 function, [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 个骰子等。我 go 如何遍历所有列表以便我可以传递任意数量的骰子并且有效吗?

使用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)

Output

[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))]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM