python-3.x - 如何计算列表中每个字母的 cout?
问题描述
我有一个大约 39000 字的列表。我需要计算列表中每个字母的出现次数,并将它们存储在字典中,其中字母为键,出现次数为值。怎么做?
有问题的清单是
['voluptuous',
'outbreak',
'starched',
'sharpest',
'widens',
'briefcase',
'stag',
'gracias',
'complexes',
'magnum',
'classifying',
'eloquent',
'forecasters',
'shepherd',
'vestments',
'indestructible',
'chartres',
'condemning',
'closet',
'davis',
'students',
.
.
.
所以,预期的输出应该是这样的
{'a': 2433,
'b': 5717,
'c': 1236,
'd': 12255,
'e': 35170,
'f': 4118,
'g': 8630,
'h': 7327,
'i': 26075,
'j': 6430,
'k': 2965,
'l': 16703,
'm': 8672,
'n': 22630,
'o': 19199,
'p': 8543,
'q': 5325,
'r': 22104,
's': 23730,
't': 20649,
'u': 10196,
'v': 3427,
'w': 2799,
'x': 828,
'y': 5344,
'z': 1031}
解决方案
这是使用的变体collections.Counter
:
from collections import Counter
counter = Counter()
words = ['voluptuous',
'outbreak',
'starched',
'sharpest',
'widens',
'briefcase',
'stag',
'gracias',
'complexes',
'magnum',
'classifying',
'eloquent',
'forecasters',
'shepherd',
'vestments',
'indestructible',
'chartres',
'condemning',
'closet',
'davis',
'students']
for word in words:
counter += Counter(word)
或在一行中:
counter = Counter(char for word in words for char in word)
推荐阅读
- javascript - 对于每个服务器,我如何使用 discord.js 创建设置
- javascript - Microsoft bot framework v4 使用 javascript 在网站中嵌入为最小化窗口
- python-3.x - Hackerrank 问题在时间限制内不适用于大数据(打印最大元素的堆栈问题)
- assembly - 猜 MIPS 中的数字
- scala - 如何最好地读取文件并转换为 spark sqlContext 数据集
- php - 设置和合并“就地”:它会导致问题吗?
- javascript - 如果使用 reactjs 空闲 15 分钟,有没有办法每 15 分钟刷新一次浏览器页面
- xcode - 您的 Xcode 项目需要迁移
- java - 如何不重复 else 语句
- jupyter-notebook - 在 watson 中创建 jupyter notebook