在循环中掷骰子:def dice(n):
total = 0
for i in range(n):
total += random.randint(1, 6)
return total
当对整数求和时,+=增广赋值运算符基本上归结为与total = total + random.randint(1, 6)相同的事情(它稍微复杂一些,但这只对列表之类的可变对象有意义)。def dice(n):
return sum(random.randint(1, 6) for _ in range(n))
这基本上与第一个示例中的for循环做相同的事情;循环n次,将1到6之间的许多随机数相加。
如果不是滚动n次,而是需要生成两个骰子滚动的n结果,则仍然需要在循环中滚动,并且需要将结果添加到列表中:def dice(n):
rolls = []
for i in range(n):
two_dice = random.randint(1, 6) + random.randint(1, 6)
rolls.append(two_dice)
return rollsdef 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
本文介绍了如何使用Python进行掷骰子模拟实验,包括单个骰子和两个骰子的投掷,通过for循环和内置函数实现,以及生成随机结果列表的方法。
5800

被折叠的 条评论
为什么被折叠?



