简体   繁体   中英

How to find most repeated element in a list Python?

I'm currently using Counter() method for this. But the issue I'm facing is that when there are multiple elements with same number of values I'm getting the out of key value of number which occurs first in the list.

a=[1,3,2,2,3]  
coun=Counter(a)
print(coun.most_common(1))

Output: [(3,2)]

a=[1,2,3,2,3]  
coun=Counter(a)
print(coun.most_common(1))

Output: [(2,2)]

I want to get the key value which is lower instead of the one that occurs first ie 2 here irrespective of the order. I could sort the list but I'm considering that sorting can use up a lot of time. Please help Sorry for the formatting mess.

Depending on the amount of duplicates you are expecting you could simply check more of the most_common values? Assuming that there's no more than 100 values with exactly the same amount you could simply do:

print(sorted(coun.most_common(100))[0])

You could use a different values for 100 of course. But now the list to sort would be at most 100 tuples, which of course isn't a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM