骰子计数器错误

时间:2015-03-07 17:16:16

标签: python python-2.7

我在python 2.7中制作了一个程序,它将滚动骰子,然后计算每个数字被滚动的次数。但似乎无法弄清楚这个问题。

它返回:Traceback(最近一次调用最后一次):   文件" DiceRoller.py",第16行,in     counter [s] + = 1 KeyError:3     来自随机导入randint

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.") 

2 个答案:

答案 0 :(得分:2)

您将每个计数器设置为值+1

counter[s] =+ 1
#           ^^^

您没有在那里使用+=; Python将其视为:

counter[s] = (+1)

交换+=

counter[s] += 1

这会引发异常,因为第一次键s不会出现;在这种情况下使用counter.get()获取默认值:

counter[s] = counter.get(s, 0) + 1

或使用collections.defaultdict() object而不是常规词典:

from collections import defaultdict

counter = defaultdict(int)
for s in dice.itervalues():
    counter[s] =+ 1

或使用collections.Counter() object进行计数:

from collections import Counter

counter = Counter(dice.itervalues())

答案 1 :(得分:0)

使用xrange并随时增加每个计数,如果你只想计算每一方滚动的次数,则不需要使用两个dicts:

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)