Python 3 elegant way to find most/less common element in a list

Опубликовано: 23 Октябрь 2024
на канале: Softhints - Python, Linux, Pandas
1,544
6

How to find the most/less common element of a list or statistics for the elements in a list. Using two different ways:
Counter from collections
count and set
Testing performance of both methods with python 3.6

Python 3 Find Most or Less Common Elements of a List

http://blog.softhints.com/python-3-fi...

Code examples

find less common
from collections import Counter
cnt = Counter()
for my_list in [5, 3, 7, 5, 3, 7, 3, 14, 12, 5, 6, 11, 3]:
cnt[my_list] -= 1
print(cnt.most_common(5))
print(cnt)

find most common
from collections import Counter
cnt = Counter()
for my_list in [5, 3, 7, 5, 3, 7, 3, 14, 12, 5, 6, 11, 3]:
cnt[my_list] += 1
print(cnt.most_common(1))
print(cnt)

find most common
my_list = [5, 3, 7, 5, 3, 7, 3, 14, 12, 5, 6, 11, 3]
print(max(set(my_list), key=my_list.count))



---------------------------------------------------------------------------------------------------------------------------------------------------------------
Code store

https://bitbucket.org/softhints/

Socials

Facebook:   / 435421910242028  
Facebook:   / softhints  
Twitter:   / softwarehints  
Discord:   / discord  


If you really find this channel useful and enjoy the content, you're welcome to support me and this channel with a small donation via PayPal.

PayPal donation https://www.paypal.me/fantasyan