簡體   English   中英

檢查數字在python詞典中出現多少次?

[英]Checking how many times a digit appears in a dictionary in 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}

為此,請使用collections.Counter無需重新發明輪子。

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

你應該改變

d[numbers] += 1

=>

d[i] += 1

我認為您想要的實際上是這樣的:

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

您應該使用collections.Counter

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

我建議使用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