Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
Theodor Avatar asked Nov 09 '10 09:11

Theodor


People also ask

How do you count repeated values in Python?

Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.

How many duplicate elements are in a set Python?

A set does not hold duplicate items. The elements of the set are immutable, that is, they cannot be changed, but the set itself is mutable, that is, it can be changed. Since set items are not indexed, sets don't support any slicing or indexing operations.


1 Answers

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
like image 158
John La Rooy Avatar answered Nov 24 '22 00:11

John La Rooy