计算字符串列表中的特定单个字母

时间:2018-11-13 00:13:38

标签: python python-3.x

注意:不是重复的。我想知道每个字母的单独计数,您张贴为重复的字母给出了每个字母的总数。

我正在尝试计算存储在列表中的所有字符串中的单个字母。

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)

此刻将产生结果:

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

但是我真正想要实现的结果是:

a = 4
b = 5
c = 6

我可以使用其他功能来计算列表中字符串中的各个字母吗?

1 个答案:

答案 0 :(得分:2)

当然!使用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})