【问题标题】:default dict counts for spaces in pythonpython中空格的默认dict计数
【发布时间】: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


【解决方案1】:

改变这一行

ct = count_var('big data examiner')

ct = count_var('big data examiner'.split())

这将计算单词而不是字符。并回答为什么要计算空格,因为空格是有效字符,就像任何字母或数字一样,所以它会被计算在内。

另请注意,存在更适合为您解决此问题的 collections.Counter,尤其是因为您已经从 collections 导入。

编辑

关于如何使用collections.Counter,上面的想法也是一样的。

这算字符

>>> Counter('big data examiner')
Counter({'a': 3, 'i': 2, 'e': 2, ' ': 2, 't': 1, 'b': 1, 'n': 1, 'd': 1, 'm': 1, 'g': 1, 'x': 1, 'r': 1})

这算字数

>>> Counter('big data examiner'.split())
Counter({'big': 1, 'data': 1, 'examiner': 1})

编辑#2计算所有非空格字符

您可以使用str.replace(' ', '')

>>> from collections import Counter
>>> Counter('big data examiner'.replace(' ', ''))
Counter({'a': 3, 'i': 2, 'e': 2, 'x': 1, 'b': 1, 'r': 1, 'g': 1, 'n': 1, 't': 1, 'm': 1, 'd': 1})

【讨论】:

  • 这里的拆分是做什么的?
  • @dangerous 它总是做什么:read the docs!
  • @dangerous str.split 将根据提供的分隔符将字符串解析为标记列表。如果没有提供分隔符,它将在空白处分割。
  • @Cyber​​ 我想要这样的输出,我不需要文字,我只需要不包括空格的字符。计数器({'a':3,'i':2,'e':2,'t':1,'b':1,'n':1,'d':1,'m':1 , 'g': 1, 'x': 1, 'r': 1})
  • @dangerous 你为什么不忽略你下一步使用的空格?
【解决方案2】:

回答具体问题:

为什么默认 dict 会计算我列表中的空格数?

因为空格仍然是字符。例如:

>>> list('big data examiner')
['b', 'i', 'g', ' ', 'd', 'a', 't', 'a', ' ', 'e', 'x', 'a', 'm', 'i', 'n', 'e', 'r']
               # ^                        ^

按照目前的编写,您的代码计算每个字符,包括空格。如果您想从计数中排除空格,您需要明确说明

def count_var(word):
    d = defaultdict(int)
    for val in word:
        if val != ' ':  # exclude spaces
            d[val]+=1
    return d

或者,不要将' ' 从计数过程中排除,只需不要在接下来对d 执行的任何操作中使用该键


注意collections 还提供Counter,可以显着简化您的代码:

>>> from collections import Counter
>>> Counter(char for char in 'big data examiner' if char != ' ')
Counter({'a': 3, 'e': 2, 'i': 2, 'b': 1, 'd': 1, 'g': 1, 'm': 1, 'n': 1, 'r': 1, 't': 1, 'x': 1})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    相关资源
    最近更新 更多