在元组列表中构建骰子组合

时间:2019-02-25 20:02:17

标签: python

需要编写一个名为build_all_dice_pairs的函数,该函数生成表示两个骰子掷骰的所有排列的元组。我必须使用一种理解来解决这个问题。

以下是我试图通过测试的某些特定代码:

def build_all_dice_pairs():
  dice_values = []
  dice = tuple(n for n in range(1,7))
  dice2 = tuple(i for i in range(1,7))
  print(dice)
  print(dice2)
  dice_values.append(dice)
  dice_values.append(dice2)
  print(dice_values)

  return

2 个答案:

答案 0 :(得分:1)

问题尚不清楚,但是尝试一下可能会帮助您:

python

结果:

from itertools import product

myList = list(product(range(1,7), repeat=2)) # the second argument can be however
                                            # many die you want to roll.
print (myList)

答案 1 :(得分:0)

即使您的问题不清楚。到目前为止,据我了解,您仍然需要两个骰子的所有可能组合。这是一个更好,更简单的解决方案:

def build_all_dice_pairs():

dice = tuple(n for n in range(1,7))

dice_values = []

for x in dice:
    for y in dice:
        dice_values.append([x,y])

# print(dice_values)
return dice_values

formated_values = build_all_dice_pairs() 打印(formated_values)

您也可以观看我2分钟的视频,以了解此代码的工作原理... https://youtu.be/NtG0mrNc3_k