“histogram”函数:输入字符串和输出字典

时间:2014-11-24 18:23:28

标签: python dictionary histogram

我正在尝试创建一个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} 

2 个答案:

答案 0 :(得分:3)

它是collections.Counter的用途:

>>> 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})

答案 1 :(得分:2)

我不会为你解决这个问题,但会给你一个提示:使用collections.Counter。将此与字符串可迭代的事实相结合,这使您非常接近解决方案。

相关问题