2013-04-04 90 views
1

我試圖檢查一個數字出現在字典中的次數。檢查一個數字在python字典中出現的次數?

此代碼僅適用於輸入單個數字的情況。

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} 

回答

2

你或許應該改變

d[numbers] += 1 

=>

d[i] += 1 
+0

哦,我知道了,謝謝 – Jett 2013-04-04 05:31:01

3

使用collections.Counter代替 - 不需要重新發明輪子。

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

我想你想要的其實是這樣的:

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

您應該使用collections.Counter

from collections import Counter 
numbers = input("Enter numbers: ") 
count = Counter(numbers) 
for c in count: 
    print c, "occured", count[c], "times" 
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) 
相關問題