How do I find the most duplicate items in lists?
def print_most_numbers_occurrences(numbers_str):
number_list = numbers_str.split()
for i in number_list:
i=max(number_list,key=number_list.count)
print(i)
def test_print_most_numbers_occurrences():
print_most_numbers_occurrences('2 3 40 1 5 4 3 3 9 9')
print_most_numbers_occurrences('9 30 3 9 3 1 4')
print_most_numbers_occurrences('19 30 13 4 9 3 1 4')
def main():
test_print_most_numbers_occurrences()
main()
output:
3 9 4
I want to get all the most duplicate numbers for '9 30 3 9 3 1 4'
: 9 and 3 appear twice, so both occurrences must be reported not only9
the output looks like this:
3 9 3 4
source to share
First: you don't need for
-loop when you use max
. It already does it for you.
Second, if you want more than one value, then max
it really isn't a good choice. For these counting operations you should use collections.Counter
(it also avoids counting the number of occurrences multiple times).
from collections import Counter
def print_most_numbers_occurrences(numbers_str):
number_list = numbers_str.split()
# count the occurrences
cnts = Counter(number_list)
# Get the maximum count
maximum_cnt = max(cnts.values())
# print all values that have the "maximum" count
print(*[val for val, cnt in cnts.items() if cnt == maximum_cnt])
And the test with your inputs prints:
3
9 3
4
If you prefer simple loops over understands (or using python-2.x without a function print
), you can also use:
def print_most_numbers_occurrences(numbers_str):
number_list = numbers_str.split()
cnts = Counter(number_list)
maximum_cnt = max(cnts.values())
for value, cnt in cnts.items():
if cnt == maximum_cnt:
print(value)
which gives:
3 9 3 4
source to share
from collections import Counter
a = ('2 3 40 1 5 4 3 3 9 9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4')
for x in a:
x = x.split()
b = Counter(x)
z = max(b.values())
for k in b.keys():
if b[k] == z:
print(k)
output:
3 9 3 4
If you want a different output
from collections import Counter
a = ('2 3 40 1 5 4 3 3 9 9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4')
k = []
for x in a:
x = x.split()
b = Counter(x)
z = max(b.values())
k.append([f for f in b.keys() if b[f] == z])
print(k)
Output
[['3'], ['9', '3'], ['4']]
Using the function
from collections import Counter
def maxmy(sequences):
k = []
for x in sequences:
x = x.split()
b = Counter(x)
z = max(b.values())
k.append([f for f in b.keys() if b[f] == z])
return k
maxmy(('2 3 40 1 5 4 3 3 9 9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4'))
Output
[['3'], ['9', '3'], ['4']]
source to share