如何计算Python3中未排序的字符串列表中元素的频率?

buh*_*htz 0 python-3.x

这段代码使用List Comprehension什么是无效的.

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}
Run Code Online (Sandbox Code Playgroud)

什么是更好的方法来计算这个未排序列表中的字符串而不会丢失字符串与其计数之间的连接?

Reu*_*ani 5

使用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})
Run Code Online (Sandbox Code Playgroud)