Counting each letter's frequency in a string

后端 未结 2 1273
梦毁少年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: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
    

提交回复
热议问题