2016-07-29 4 views
0

このコードでは、List Comprehensionを使用して非効率的なものを示します。文字列とそのカウントの間connectinoを失うことなく、このソートされていないリスト内の文字列をカウントするためのより良い方法だろう何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} 

答えて

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}) 
関連する問題