简体   繁体   English

检查数字在python词典中出现多少次?

[英]Checking how many times a digit appears in a dictionary in python?

I'm trying to check how many times a digit appears in a dictionary. 我正在尝试检查数字在词典中出现了多少次。

This code only works if I input a single 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)

For example if I input 8 the output will be 例如,如果我输入8则输出为

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

But if I input 887655 then it gives me a builtins.KeyError: '887655' 但是,如果我输入887655那么它会给我一个builtins.KeyError: '887655'

If I input 887655 the output should actually be 如果我输入887655 ,输出实际上应该是

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

Use collections.Counter for this instead - no need to reinvent the wheel. 为此,请使用collections.Counter无需重新发明轮子。

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

You should probably change 你应该改变

d[numbers] += 1

=> =>

d[i] += 1

I think what you want is actually this: 我认为您想要的实际上是这样的:

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

You should use collections.Counter 您应该使用collections.Counter

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

I would recommend collections.Counter but here's an improved version of your code: 我建议使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM