【发布时间】:2015-04-17 01:25:17
【问题描述】:
为什么默认 dict 会计算我列表中的空格数?
我使用默认字典计算字符在单词中出现的次数。但是我的代码也计算了单词之间的空格数。那么如何只计算单词的出现而忽略单词中出现的空格。
from collections import defaultdict
def count_var(word):
d = defaultdict(int)
for val in word:
d[val]+=1
return d
ct = count_var('big data examiner')
print ct
defaultdict(<type 'int'>, {'a': 3, ' ': 2, 'b': 1, 'e': 2, 'd': 1, 'g': 1, 'i': 2, 'm': 1, 'n': 1, 'r': 1, 't': 1, 'x': 1})
【问题讨论】:
-
为什么不呢?你为什么不直接使用
collections.Counter?! -
@jonrsharpe 你能用计数器复制同样的代码吗?
-
为什么不read the docs,试试看,看看?但请记住,当答案是“因为你不能使用 [whatever] 来做到这一点”时,人们很少会问这样的问题...
-
@jonrsharpe 但即使是计数器也会计算空格。
-
@dangerous 哦,可惜...
Counter只是简化了您的代码。如果你想让它计算 words,而不是 characters(包括空格),你必须传递 words 而不是 characters。
标签: python dictionary