检查数字在python中的字典中出现的次数?

时间:2013-04-04 05:27:39

标签: python dictionary digit

我正在尝试查看数字出现在字典中的次数。

此代码仅在我输入单个数字时有效。

numbers = input("Enter numbers ")

d = {}
d['0'] = 0
d['1'] = 0
d['2'] = 0
d['3'] = 0
d['4'] = 0
d['5'] = 0
d['6'] = 0
d['7'] = 0
d['8'] = 0
d['9'] = 0

for i in numbers:
    d[numbers] += 1

print(d)

例如,如果输入8,输出将为

{'8': 1, '9': 0, '4': 0, '5': 0, '6': 0, '7': 0, '0': 0, '1': 0, '2': 0, '3': 0}

但如果我输入887655,那么它会给我一个builtins.KeyError: '887655'

如果我输入887655,则输出实际应为

{'8': 2, '9': 0, '4': 0, '5': 2, '6': 1, '7': 1, '0': 0, '1': 0, '2': 0, '3': 0}

5 个答案:

答案 0 :(得分:3)

使用collections.Counter代替 - 无需重新发明轮子。

>>> import collections
>>> collections.Counter("887655")
Counter({'8': 2, '5': 2, '6': 1, '7': 1})

答案 1 :(得分:2)

你应该改变

d[numbers] += 1

=>

d[i] += 1

答案 2 :(得分:0)

我认为你想要的实际上是这样的:

for number in numbers:
    for digit in str(number):
        d[digit] += 1

答案 3 :(得分:0)

您应该使用collections.Counter

from collections import Counter
numbers = input("Enter numbers: ")
count = Counter(numbers)
for c in count:
    print c, "occured", count[c], "times"

答案 4 :(得分:0)

我建议使用collections.Counter,但这是代码的改进版本:

numbers = input("Enter numbers ")

d = {} # no need to initialize each key

for i in numbers:
    d[i] = d.get(i, 0) + 1 # we can use dict.get for that, default val of 0

print(d)