【问题标题】:How to loop through an n-dimensional list and find all combinations如何遍历n维列表并找到所有组合
【发布时间】:2021-11-24 02:47:24
【问题描述】:

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

【问题讨论】:

    标签: python arrays list dice


    【解决方案1】:

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

    from itertools import product
    
    dice = [4, 6]
    
    individual_outcomes = [range(1, d+1) for d in dice]
    
    combined_outcomes = [*map(sum, product(*individual_outcomes))]
    

    【讨论】:

    • list(map(sum, product(*individual_outcomes)))相比,您的方法有什么优势吗?
    • 3字节代码:D
    【解决方案2】:

    使用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,上述代码保持不变。

    【讨论】:

      猜你喜欢
      • 2017-03-17
      • 2020-02-21
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      相关资源
      最近更新 更多