Count the number of elements of same value in Python [duplicate]
Possible Duplicate:
How to count the frequency of the elements in a list?
I wish to count the number of elements of same value in a list and return a dict as such:
> a = map(int,[x**0.5 for x in range(20)])
> a
开发者_开发技巧> [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
> number_of_elements_by_value(a)
> {0:1, 1:3, 2:5, 3:7, 4:4}
I guess it is kind of a histogram?
This is a good way if you don't have collections.Counter
available
from collections import defaultdict
d = defaultdict(int)
a = map(int, [x**0.5 for x in range(20)])
for i in a:
d[i] += 1
print d
Use a Counter:
>>> from collections import Counter
>>> a = map(int,[x**0.5 for x in range(20)])
>>> a
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
>>> c = Counter(a)
>>> c[2]
5
Use count to get the count of an element in list and set for unique elements:
>>> l = [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
>>> k = [(x, l.count(x)) for x in set(l)]
>>> k
[(0, 1), (1, 3), (2, 5), (3, 7), (4, 4)]
>>>
>>>
>>> dict(k)
{0: 1, 1: 3, 2: 5, 3: 7, 4: 4}
>>>
Before there was Counter, there was groupby:
>>> a = map(int,[x**0.5 for x in range(20)])
>>> from itertools import groupby
>>> a_hist= dict((g[0],len(list(g[1]))) for g in groupby(a))
>>> a_hist
{0: 1, 1: 3, 2: 5, 3: 7, 4: 4}
(For groupby to work for this purpose, the input list a
must be in sorted order. In this case, a
is already sorted.)
精彩评论