I have a two list as follows
x = ['a','a','b','c','b','a']
and
x = ['a','a','b','c','c','d']
I'm trying to find which values occur the most in each of these lists. This is what I have tried.
def unique_values(output,input):
for i in input:
if i not in output:
output.append(i)
k = []
for i in k:
unique_values(k,x)
y.remove(i)
I've gotten this far but I cant figure out how to stop the for i in k:
before it removes all the values in the list.
Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.
Given a list, the task is to find the number of occurrences of the largest element of the list. Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list.
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.
You can use Counter
module from collections
, if you want to find the occurrences of each element in the list: -
>>> x = ['a','a','b','c','c','d']
>>> from collections import Counter
>>> count = Counter(x)
>>> count
Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1})
>>> count.most_common()
[('a', 2), ('c', 2), ('b', 1), ('d', 1)]
So, the first two elements are most common in your list.
>>> count.most_common()[0]
('a', 2)
>>> count.most_common()[1]
('c', 2)
or, you also pass parameter to most_common()
to specify how many most-common
elements you want: -
>>> count.most_common(2)
[('a', 2), ('c', 2)]
Update : -
You can also find out the max
count first, and then find total number of elements with that value, and then you can use it as parameter in most_common()
: -
>>> freq_list = count.values()
>>> freq_list
[2, 2, 1, 1]
>>> max_cnt = max(freq_list)
>>> total = freq_list.count(max_cnt)
>>> most_common = count.most_common(total)
[('a', 2), ('c', 2)]
>>> [elem[0] for elem in most_common]
['a', 'c']
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