Home > Backend Development > Python Tutorial > Python finds the most frequently occurring elements in a list

Python finds the most frequently occurring elements in a list

高洛峰
Release: 2017-03-02 11:33:51
Original
1651 people have browsed it

The examples in this article describe Python’s method of finding the most frequently occurring elements in a list. Share it with everyone for your reference, the details are as follows:

Assume that a list contains various elements, you need to count the number of occurrences of each element, and print out the top three most frequently occurring elements. What are the differences. The list is as follows:

Copy code The code is as follows:

word_list =["is","you","are","I","am ","OK","is","OK","She","is","OK","is","I"]

Method one (conventional method):

>>> word_counter ={}
>>> for word in word_list:
  if word in word_counter:
    word_counter[word] +=1
  else:
    word_counter[word] = 1
>>> popular_word =sorted(word_counter, key = word_counter.get, reverse = True)
)
>>> top_3 = popular_word[:3]
>>> top_3
['is', 'OK', 'I']
Copy after login

Method 2: Applicable to Python2.7

>>> from collections import Counter
>>> c = Counter(word_list)
>>> c.most_common(3)
Copy after login

Method 3:

>>> counter ={}
>>> for i in word_list: counter[i] = counter.get(i, 0) + 1
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(4, 'is'), (3, 'OK'), (2, 'I')]
Copy after login


##For more Python related articles on finding the most frequently occurring elements in a list, please Follow PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template