2014-11-24 90 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