Python finds out the most common element in the list, and python finds out the list element.

Source: Internet
Author: User

Python finds out the most common element in the list, and python finds out the list element.

This example describes how to find the most common element in the list using Python. We will share this with you for your reference. The details are as follows:

Assuming that a list contains various elements, You need to count the number of each element and print out the first three elements that most often appear. List:
Copy codeThe Code is as follows: word_list = ["is", "you", "are", "I", "am", "OK", "is", "OK ", "She", "is", "OK", "is", "I"]

Method 1 (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']

Method 2: Applicable to Python2.7

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

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')]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.