I'm having a list as shown here. a=[1936,2401,2916,4761,9216,9216,9604,9801]
I want to get the value which have more duplicates. In here it is '9216' how can i get this value? Thanks
If you just want to find most common number in a list, you can use a simple formula. Select a blank cell, here is C1, type this formula =MODE(A1:A13), and then press Enter key to get the most common number in the list.
count(number) #checks how many times that unique number appears in the original list if count > most_common[1] #if the count is greater than the most_common count most_common = [number, count] #resets most_common to the current number and count print(str(most_common[0]) + " is listed " + str(most_common[1]) + "times!")
You can use collections.Counter
for this:
from collections import Counter
a = [1936, 2401, 2916, 4761, 9216, 9216, 9604, 9801]
c = Counter(a)
print(c.most_common(1)) # the one most common element... 2 would mean the 2 most common
[(9216, 2)] # a set containing the element, and it's count in 'a'
From the docs:
There's two standard library ways to do this:
statistics.mode
:
from statistics import mode
most_common = mode([3, 2, 2, 2, 1]) # 2
most_common = mode([3, 2]) # StatisticsError: no unique mode
collections.Counter.most_common
:
from collections import Counter
most_common, count = Counter([3, 2, 2, 2, 1]).most_common(1)[0] # 2, 3
most_common, count = Counter([3, 2]).most_common(1)[0] # 3, 1
Both are identical in terms of performance, but the first raises an exception when there is no unique most common element and the second returns the frequency as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With