问题描述
我制作了一个双面骰子随机生成器,但我需要让程序在底部打印出来 1 被滚动 x 次 2 被滚动 x 次 等等。 我怎样才能做到这一点。
我的代码是:
import random
print("Six sided dice programme")
count = 1
while True:
answer = str(input("would you like to roll,'y' for yes,'n' for no:"))
if answer == 'y':
roll=random.randint(1,6)
print("roll number",str(count),":",roll)
count = count + 1
if answer == "n":
print("Game over")
break
解决方法
您将计数保存在整数 count
变量中。更改为表示骰子每一面计数的列表/字典。
列表:
import random
counts = [0] * 6
for i in range(10):
roll = random.randint(1,6)
print("roll number",i,":",roll)
counts[roll-1] += 1
for side,count in enumerate(counts):
print(side+1,"was rolled",count,"amount of times")
字典:
import random
from collections import defaultdict
counts = defaultdict(int)
for i in range(10):
roll = random.randint(1,i+1,roll)
counts[roll] += 1
for side,count in counts.items():
print(side,"amount of times")
* 这将按照每边第一次出现的顺序打印计数