2014-12-06 65 views
0

我知道有可以做這種行爲的模塊,但我對如何處理下面的「問題」感興趣。沒有檢查一個單詞是否在「在」字典中計數單詞

每當我曾經想指望出現,我發現它有點傻,我不得不首先檢查鑰匙是否爲「在」詞典(#1)。我相信當時我甚至使用了一種嘗試......異常,因爲我不知道如何正確地做到這一點。

# 1 
words = ['a', 'b', 'c', 'a', 'b'] 
dicty = {} 
for w in words: 
    if w in dicty: 
     dicty[w] += 1 
    else: 
     dicty[w] = 1 

在這個時刻,我很感興趣的是有工作要做,以使一個類「SpecialDictionary」行爲,例如,如果一個字不在字典,它會自動獲得一個默認值0(問題#2)。這個問題需要哪些概念?

注意:我知道這個「in」檢查可以在班級的定義中完成,但是必須有更多pythonic /優雅的東西嗎?

# 2 
special_dict = SpecialDictionary()   
for w in words: 
    special_dict[w] += 1 

回答

2

子類dict並覆蓋其__missing__方法返回0:

class SpecialDictionary(dict): 
    def __missing__(self, k): 
     return 0 

words = ['a', 'b', 'c', 'a', 'b'] 
special_dict = SpecialDictionary()   
for w in words: 
    special_dict[w] += 1 
print special_dict 
#{'c': 1, 'a': 2, 'b': 2} 
+0

這就是它,非常感謝。非常酷的答案! – PascalVKooten 2014-12-06 20:05:51

2

您需要使用dict.get

>>> my_dict = {} 
>>> for x in words: 
...  my_dict[x] = my_dict.get(x,0) + 1 
... 
>>> my_dict 
{'a': 2, 'c': 1, 'b': 2} 

dict.get返回鍵的值,如果存在的話,否則默認
語法:dict.get(key,[default])

你也可以使用嘗試和除,如果在字典中找不到密鑰,則會提高keyError

>>> for x in words: 
...  try: 
...   my_dict[x] += 1 
...  except KeyError: 
...   my_dict[x] = 1 
... 
>>> my_dict 
{'a': 2, 'c': 1, 'b': 2} 

使用Counter

>>> from collections import Counter 
>>> words = ['a', 'b', 'c', 'a', 'b'] 
>>> my_count = Counter(words) 
>>> my_count 
Counter({'a': 2, 'b': 2, 'c': 1}) 
+1

第一句的問題,我知道計數器。 – PascalVKooten 2014-12-06 20:04:02

+0

@PascalvKooten現在檢查它:) – Hackaholic 2014-12-06 20:07:20

+0

似乎沒有最有效的性能?仍然反例是非常無效的。 +1的創意解決方案,但已經給出了最佳答案:) – PascalVKooten 2014-12-06 20:08:38

0

可以使用defaultdict。或者,這是你想避免的「模塊之一」嗎?

from collections import defaultdict 
d = defaultdict(lambda : 0) 
d['a'] += 1 
print(d['a']) 
print(d['b']) 

它會打印:

1 
0 
+0

是的,我想這是一個模棱兩可的問題,我大多隻是在自己的方式感興趣。 – PascalVKooten 2014-12-06 20:05:18

0

的 'SpecialDictionary' 實現這種行爲是collections.defaultdict。它將一個函數作爲第一個參數作爲默認值工廠。當執行查找時,它會檢查密鑰是否已經存在於字典中,如果不是,則使用該工廠函數創建一個值,然後將其添加到字典中(並由查找返回)。有關如何實施,請參閱docs

Counterdefaultdict的一個特殊的變種,它使用int值作爲工廠的功能(並提供一些額外的方法)