Counting letter occurances Python

前端 未结 2 1378
攒了一身酷
攒了一身酷 2021-01-15 04:12

I am trying to count letter occurances and print them. This is what i have so far:

def histogram(L):
    d = {}
    for x in L:
      for letter in x:
               


        
2条回答
  •  暖寄归人
    2021-01-15 04:20

    d is a dictionary, not a list. Loop over the keys:

    for key in d:
        print('{} | {}'.format(key, d[key]))
    

    or you'll get KeyError exceptions.

    You may be interested in the collections.Counter() class; it's a counting dictionary:

    from collections import Counter
    
    def histogram(L):
        d = Counter(letter for line in L for letter in x)
        for letter in d:
            print('{} | {}'.format(letter, d[letter]))
        return d
    

提交回复
热议问题