2016-07-29 57 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}) 
相关问题