【问题标题】:Counting each letter's frequency in a string计算字符串中每个字母的频率
【发布时间】:2012-06-04 03:10:24
【问题描述】:

这是一个来自 pyschools 的问题。

我确实做对了,但我猜会有更简单的方法。这是最简单的方法吗?

def countLetters(word):
    letterdict={}
    for letter in word:
        letterdict[letter] = 0
    for letter in word:
        letterdict[letter] += 1
    return letterdict

这应该看起来像这样:

>>> countLetters('google')
{'e': 1, 'g': 2, 'l': 1, 'o': 2}

【问题讨论】:

    标签: python dictionary


    【解决方案1】:
    >>> import collections
    >>> print collections.Counter("google")
    Counter({'o': 2, 'g': 2, 'e': 1, 'l': 1})
    

    【讨论】:

      【解决方案2】:

      在 2.7+ 中:

      import collections
      letters = collections.Counter('google')
      

      更早(2.5+,现在很古老):

      import collections
      letters = collections.defaultdict(int)
      for letter in word:
          letters[letter] += 1
      

      【讨论】:

      • 这个操作的时间复杂度是多少?
      猜你喜欢
      • 2023-03-25
      • 2018-09-08
      • 2021-12-31
      • 2017-04-20
      • 2016-07-25
      • 2019-06-04
      • 2012-10-24
      相关资源
      最近更新 更多