2014-12-06 72 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值作为工厂的功能(并提供一些额外的方法)