2016-07-29 55 views
0

這段代碼使用List Comprehension什麼是無效的。如何計算Python3中未排序字符串列表中元素的頻率?

l = ['banana', 'apple', 'linux', 'pie', 'banana', 'win', 'apple', 'banana'] 
d = {e:l.count(e) for e in l} 
d 
{'pie': 1, 'linux': 1, 'banana': 3, 'apple': 2, 'win': 1} 

什麼會是一個更好的方法來計算在此無序列表中的字符串沒有鬆動的字符串,其計之間的connectino?

回答

4

使用collections.Counter

>>> from collections import Counter 
>>> l = ['banana', 'apple', 'linux', 'pie', 'banana', 'win', 'apple', 'banana'] 
>>> Counter(l) 
Counter({'banana': 3, 'apple': 2, 'pie': 1, 'win': 1, 'linux': 1}) 
相關問題