3

Note: NOT a duplicate..I want to know the individual counts of each letter, the one you posted as duplicate gives the total count of each one.

I am trying to count the individual letters from all the strings which are stored in a list.

def countElement(a):
    g = {}
    for i in a:
        if i in g: 
            g[i] +=1
        else: 
            g[i] =1
    return g

list : ['a a b b c c', 'a c b c', 'b c c a b']



  for i in range(1000000):
        b = countElement(list)
    print(b)

At the moment this produces the result:

{'a a b b c c': 1, 'a c b c': 1, 'b c c a b': 1}

But the result that I actually want to achieve is:

a = 4
b = 5
c = 6

Is there a different function that I can use which will count the individual letters within the strings in the list?

JameshGong
  • 155
  • 10

1 Answers1

2

Sure! Use collections.Counter:

from collections import Counter


lst = ['a a b b c c', 'a c b c', 'b c c a b']

counter = Counter()
for word in lst:
    counter.update(word)

print(counter)
# Counter({' ': 12, 'c': 6, 'b': 5, 'a': 4})
Ben
  • 5,952
  • 4
  • 33
  • 44