Pour obtenir le nombre d'occurrences (répétitions) d'un élément donnée d'une liste python, on peut utiliser la method count(), exemple:
>>> 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
Si on veut obtenir une liste d'occurrences pour chaque élément de la liste on peut utiliser counter():
>>> 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)]
Références
Liens | 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 |