Counter () count in Python

Source: Internet
Author: User

One: Define a list array to find the number of occurrences of each element in the array

If implemented in Java, is a more complex, need to traverse the array list.

But Python is simple: look at the code

[Python]View Plain Copy
    1. A = [1,4,2,3,2,3,4,2]
    2. From collections Import Counter
    3. Print Counter (a)


Printing results:

Counter ({2:3, 3:2, 4:2, 1:1})

The results show that element 2 appears 3 times, Element 3 appears 2 times, element 4 occurs 2 times, and element 1 appears 1 times.

Second: Find the most frequently occurring elements in an array

Look directly at the code:

[Python]View Plain Copy
    1. A = [1,4,2,3,2,3,4,2]
    2. From collections Import Counter
    3. Print Counter (a). Most_commo (1)


Operation Result:

[(2, 3)]

Continue to modify the code:

[Python]View Plain Copy
    1. A = [1,4,2,3,2,3,4,2]
    2. From collections Import Counter
    3. Print Counter (a)
    4. Print Counter (a). Most_common (2)


Operation Result:

[(2, 3), (3, 2)]

Three: summary

(1) The collection class is introduced from the Collections Collection module counter

(2) Counter (a) can print the number of occurrences of each element in Group A

(3) Counter (a). Most_common (2) can print the most frequently occurring elements in the array. The meaning of parameter 2 is that it outputs several elements that have the most occurrences.

Transferred from: http://blog.csdn.net/u013628152/article/details/43198605

Counter () count in Python

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.