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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With