Python learning-the frequency with which elements appear in a statistical sequence (number of times)

Source: Internet
Author: User

For example, there is a list

L=[1,1,-1,2,3,22,34,32,2,-3,34,22,-5]

How many times each element appears in the statistics list

Way One:

Turn the list into a dictionary dict, the dictionary key corresponds to each element in the list, and value represents the number of occurrences of each element.

D=dict.fromkeys (l,0) #两个参数, the first parameter is the corresponding list, and the second parameter sets the default value=0 for Dict.

Then, traversing each element in the list, the element is encountered in the Dict, and value is added 1.

For X in L:

D[l]+=1

Print (d)

Way two:

Take advantage of the counter subclass of the collection.

From collections Import Counter

C=counter (L) #直接把列表l传入Counter, returns a dict, the key in this dict corresponds to each element in the set, and value represents the number of occurrences of this element in the collection

Print (C.most_common (3)) #Counter类的most_common () method returns a value from a large to a small list, returning n most common elements The list and its number.

Python learning-the frequency with which elements appear in a statistical sequence (number of times)

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.