2014-11-24 71 views
-2

我试图创建一个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

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

+0

谢谢,我会试试看 – 2014-11-24 18:39:57

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

我从来没有听说过之前收集的,但感谢你 – 2014-11-24 18:41:08

+0

欢迎您,'这个模块实现专门的容器数据类型提供替代品到Python的通用内置容器,dict,list,set和tuple.'它是python数据结构中的必要模块!试图学习它! – Kasramvd 2014-11-24 18:42:57