To find he element of a list with the maximum of repetitions (occurrences) in python, a solution is to use the function counter from the python module collections, example:
Find the element of a list with the maximum of repetitions for a list of numbers
Example with a list of numbers:
>>> from collections import Counter
>>> l = [8, 3, 9, 2, 7, 1, 3, 2, 0, 0, 7, 8, 6, 9, 4, 6, 3, 3, 2, 5]
>>> Counter(l).most_common(1)
[(3, 4)]
the function returns 3 with 4 occurrences in the list.
Note: the function Counter(l).most_common() can be used to sort the list elements in function of the occurrences:
>>> from collections import Counter
>>> l = [8, 3, 9, 2, 7, 1, 3, 2, 0, 0, 7, 8, 6, 9, 4, 6, 3, 3, 2, 5]
>>> Counter(l).most_common()
[(3, 4), (2, 3), (8, 2), (9, 2), (7, 2), (0, 2), (6, 2), (1, 1), (4, 1), (5, 1)]
Find the element of a list with the maximum of repetitions for a list of strings
Works also with a list of strings:
>>> from collections import Counter
>>> l = ['a','a','a','b','c','c','d','d','d','d']
>>> Counter(l).most_common(1)
[('d', 4)]
Sort the list in function of the occurrences:
>>> from collections import Counter
>>> Counter(l).most_common()
[('d', 4), ('a', 3), ('c', 2), ('b', 1)]
References
Links | Site |
---|---|
collections | python doc |
Python- find the item with maximum occurrences in a list | stackoverflow |
Python most common element in a list | stackoverflow |