Skip to main content
 首页 » 编程设计

python之在 Python 中模拟滚动 2 个骰子

2025年05月04日32sky-heaven

有人要求我模拟掷两个面为 1-6 的公平骰子。所以可能的结果是 2-12。

我的代码如下:

def dice(n): 
    x=random.randint(1,6) 
    y=random.randint(1,6) 
    for i in range(n): 
        z=x+y 
    return z 

我的问题是这只返回掷骰子 1 次的结果,所以结果总是 2-12。我希望它返回掷骰子 (n) 次的总和。

有人对我有什么建议吗?

请您参考如下方法:

在循环中掷骰子:

def dice(n): 
    total = 0 
    for i in range(n): 
        total += random.randint(1, 6) 
    return total 

+= 扩充赋值运算符基本上可以归结为与 total = total + random.randint(1, 6) 相同的东西,当对整数求和时(它稍微比这更复杂,但这只对像列表这样的可变对象很重要。

你甚至可以使用 generator expression和 sum() function :

def dice(n): 
    return sum(random.randint(1, 6) for _ in range(n)) 

这基本上与第一个示例中的 for 循环做同样的事情;循环 n 次,对 1 到 6 之间的许多随机数求和。

如果不是滚动 n 次,而是需要产生 n 2 次骰子滚动的结果,您仍然需要在循环中滚动,并且需要添加结果列表:

def dice(n): 
    rolls = [] 
    for i in range(n): 
        two_dice = random.randint(1, 6) + random.randint(1, 6) 
        rolls.append(two_dice) 
    return rolls 

这也可以写得更紧凑,用 list comprehension :

def dice(n): 
    return [random.randint(1, 6) + random.randint(1, 6) for _ in range(n)] 

您还可以从生成的总和列表中使用 random.choice();这些会自动正确加权;这基本上预先计算了 36 个可能的骰子值(11 个唯一值),每个值的概率相等:

from itertools import product 
 
two_dice_sums = [a + b for a, b in product(range(1, 7), repeat=2)] 
 
def dice(n): 
    return [random.choice(two_dice_sums) for _ in range(n)] 

无论哪种方式,您都会得到一个包含 n 个结果的列表:

>>> dice(5) 
[10, 11, 6, 11, 4] 
>>> dice(10) 
[3, 7, 10, 3, 6, 6, 6, 11, 9, 3] 

您可以将列表传递给 print() 函数以将这些打印在一行或单独的行上:

>>> print(*dice(5)) 
3 7 8 6 4 
>>> print(*dice(5), sep='\n') 
7 
8 
7 
8 
6