Answers for "get most common element in list python"

0

get most common element in list python

from collections import Counter

listOfArtists = [
 'Linkin Park',
 'Lil Peep',
 'Lil Peep',
 'Cold Hart',
 'Team Astro',
 'Tom Odell',
 'Bazzi',
 'The Weeknd',
 'Juice WRLD',
 'The Weeknd',
 'Foster The People',
 'Linkin Park',
 'Linkin Park',
 'Lil Peep',] 

amount = 4
print(Counter(listOfArtists).most_common(amount)) # amount = elements returned 

#output: [('Linkin Park', 3), ('Lil Peep', 3), ('The Weeknd', 2), ('Cold Hart', 1)]
Posted by: Guest on October-13-2021
3

most common elements in a list python

>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
Posted by: Guest on March-11-2020

Code answers related to "get most common element in list python"

Python Answers by Framework

Browse Popular Code Answers by Language