Python 骰子计数器错误
我正在用Python2.7制作一个掷骰子的程序,然后计算每个数字被掷的次数。但我似乎无法解决这个问题 它返回:回溯(最近一次调用last): 文件“dicerroller.py”,第16行,在 计数器[s]+=1 关键错误:3 从随机导入randintPython 骰子计数器错误,python,python-2.7,Python,Python 2.7,我正在用Python2.7制作一个掷骰子的程序,然后计算每个数字被掷的次数。但我似乎无法解决这个问题 它返回:回溯(最近一次调用last): 文件“dicerroller.py”,第16行,在 计数器[s]+=1 关键错误:3 从随机导入randint while True: z = raw_input("How many sides should the dice(s) have?\n> ") i = 0 x = raw_input("How many dices
while True:
z = raw_input("How many sides should the dice(s) have?\n> ")
i = 0
x = raw_input("How many dices do you want?\n> ")
dice = {}
while i <= int(x):
dice[i] = randint(1,int(z))
i += 1
counter = {}
for p, s in dice.iteritems():
counter[s] += 1
print counter
raw_input("Return to restart.")
为True时:
z=原始输入(“骰子应该有多少边?\n>”)
i=0
x=原始输入(“您想要多少个骰子?\n>”)
骰子={}
当i将每个计数器设置为值+1
:
counter[s] =+ 1
# ^^^
您没有在那里使用+=
;Python认为这是:
counter[s] = (+1)
交换+
和=
:
counter[s] += 1
这将引发异常,因为键s
不会第一次出现;在这种情况下,使用counter.get()
获取默认值:
counter[s] = counter.get(s, 0) + 1
或者使用字典而不是普通字典:
from collections import defaultdict
counter = defaultdict(int)
for s in dice.itervalues():
counter[s] =+ 1
或使用a进行计数:
from collections import Counter
counter = Counter(dice.itervalues())
使用xrange并在运行时增加每个计数,如果您只想计算每侧滚动的次数,则无需使用两个DICT:
from collections import defaultdict
from random import randint
z = int(raw_input("How many sides should the dice(s) have?\n> "))
x = int(raw_input("How many dices do you want?\n> "))
counts = defaultdict(int) # store dices sides as keys, counts as values
# loop in range of how many dice
for _ in xrange(x):
counts[randint(1,z)] += 1
for side,count in counts.iteritems():
print("{} was rolled {} time(s)".format(side,count))
输出:
How many sides should the dice(s) have?
> 6
How many dices do you want?
> 10
1 was rolled 2 time(s)
2 was rolled 3 time(s)
3 was rolled 1 time(s)
4 was rolled 1 time(s)
5 was rolled 1 time(s)
6 was rolled 2 time(s)
如果要在输出中包含所有骰子边,可以使用xrange创建计数dict:
counts = {k:0 for k in xrange(1, z+1)}
因此,输出将是:
How many sides should the dice(s) have?
> 6
How many dices do you want?
> 10
1 was rolled 0 time(s)
2 was rolled 2 time(s)
3 was rolled 0 time(s)
4 was rolled 0 time(s)
5 was rolled 5 time(s)
6 was rolled 3 time(s)
我切换是因为:如果我做+=1,我会得到以下错误:回溯(最近一次调用last):文件“dicerroller.py”,第16行,在计数器[s]+=1键错误:3我将修复OP@HåvardNygård:是的,因为您无法添加到字典中尚未包含的值。有关解决方案,请参阅我的更新。