順序なしリスト内の要素の頻度を数えるにはどうすればいいですか? [重複] 質問する

順序なしリスト内の要素の頻度を数えるにはどうすればいいですか? [重複] 質問する

次のような順序なしの値のリストが与えられたとします。

a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]

リストに表示される各値の頻度を次のように取得するにはどうすればよいでしょうか?

# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output

ベストアンサー1

Python 2.7(またはそれ以降)では、collections.Counter:

>>> import collections
>>> a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
>>> counter = collections.Counter(a)
>>> counter
Counter({1: 4, 2: 4, 5: 2, 3: 2, 4: 1})
>>> counter.values()
dict_values([2, 4, 4, 1, 2])
>>> counter.keys()
dict_keys([5, 1, 2, 4, 3])
>>> counter.most_common(3)
[(1, 4), (2, 4), (5, 2)]
>>> dict(counter)
{5: 2, 1: 4, 2: 4, 4: 1, 3: 2}
>>> # Get the counts in order matching the original specification,
>>> # by iterating over keys in sorted order
>>> [counter[x] for x in sorted(counter.keys())]
[4, 4, 2, 1, 2]

Python 2.6以前を使用している場合は、実装をダウンロードできます。ここ

おすすめ記事