To get the occurrences of a given element in a python list, a solution is to use count() method , example:
1 2 3 4 5 6 7 8 9 10 | >>> import random >>> l = [random.randint(0,5) for i in range(10)] >>> l [1, 3, 0, 0, 5, 1, 0, 0, 0, 4] >>> l.count(1) 2 >>> l.count(0) 5 >>> l.count(6) 0 |
To get a list of occurrences of each element in the list, a solution is to use counter() method, example:
1 2 3 4 5 | >>> from collections import Counter >>> Counter(l).most_common(1) [(0, 5)] >>> Counter(l).most_common() [(0, 5), (1, 2), (3, 1), (5, 1), (4, 1)] |
References
Links | Site |
---|---|
count() | python doc |
counter() | python doc |
How can I count the occurrences of a list item? | stackoverflow |
How to find all occurrences of an element in a list? | stackoverflow |
Python List Comprehensions: Explained Visually | treyhunner.com |