“直方图”功能:输入字符串和输出字典

2024-04-19 06:14:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个histogram函数,它接受字符串并计算字符串被使用并放入字典的次数。我还在学习Python,所以任何提示都会有帮助。你知道吗

>>> histogram('The Goose that Laid the Golden Egg') 
{'l': 2, 'n': 1, 'o': 3, 'h': 3, 'i': 1,'d': 2,   'e': 5, 'g': 4, ' ': 6, 'a': 2, 't': 4, 's': 1} 

Tags: the函数字符串字典thategg次数histogram
2条回答

这就是^{}的用途:

>>> from collections import Counter
>>> Counter('The Goose that Laid the Golden Egg')
Counter({' ': 6, 'e': 4, 'h': 3, 'o': 3, 't': 3, 'a': 2, 'd': 2, 'G': 2, 'g': 2, 'i': 1, 'L': 1, 'l': 1, 's': 1, 'T': 1, 'E': 1, 'n': 1})

我不会为您解决这个问题,但会给您一个提示:使用^{}。再加上字符串是可iterable的,这就很接近于一个解决方案。你知道吗

相关问题 更多 >