Counting each letter's frequency in a string

后端 未结 2 1262
梦毁少年i
梦毁少年i 2020-11-27 07:14

This is a question from pyschools.

I did get it right, but I\'m guessing that there would be a simpler method. Is this the simplest way to do this?



        
相关标签:
2条回答
  • 2020-11-27 07:42
    >>> import collections
    >>> print collections.Counter("google")
    Counter({'o': 2, 'g': 2, 'e': 1, 'l': 1})
    
    0 讨论(0)
  • 2020-11-27 07:44

    In 2.7+:

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

    Earlier (2.5+, that's ancient by now):

    import collections
    letters = collections.defaultdict(int)
    for letter in word:
        letters[letter] += 1
    
    0 讨论(0)
提交回复
热议问题