计算python多维列表中每个字符的出现

时间:2018-06-22 05:36:37

标签: python-3.x

我想计算以下列表中每个字符的出现:

messages=['It is certain',
          'It is decidedly so',
          'Yes definitely',
          'Reply hazy try again',
          'Ask again later',
          'Concentrate and ask again',
          'My reply is no',
          'Outlook not so good',
          'Very doubtful']

我的代码是这样的:

a=dict((letter,messages.count(letter))for letter in set(messages))
print(a)

输出为:

{'Yes definitely': 1, 'Very doubtful': 1, 'It is decidedly so': 1, 'Outlook not so good': 1, 'Reply hazy try again': 1, 'It is certain': 1, 'My reply is no': 1, 'Concentrate and ask again': 1, 'Ask again later': 1}

这是对列表中的每个元素进行计数,而不是我想要对每个字符进行计数。

1 个答案:

答案 0 :(得分:0)

有多种方法可以做到这一点,一种怪诞的方法是:

messages=['It is certain','It is decidedly so','Yes definitely','Reply hazy try again','Ask again later','Concentrate and ask again','My reply is no','Outlook not so good','Very doubtful']

characters = list(''.join(messages).replace(" ","").lower())

characters.sort()
from itertools import groupby
count = {key:len(list(group)) for key, group in groupby(characters)}

print(count)

{'a': 13, 'b': 1, 'c': 4, 'd': 7, 'e': 12, 'f': 2, 'g': 4, 'h': 1, 'i': 12, 'k': 3, 'l': 7, 'm': 1, 'n': 10, 'o': 11, 'p': 2, 'r': 7, 's': 8, 't': 11, 'u': 3, 'v': 1, 'y': 9, 'z': 1}