The methods in the Counter class of the python3 collections module are listed.

Source: Internet
Author: User

The methods in the Counter class of the python3 collections module are listed.

Counter: the number of times that a Counter appears.

Counter class inherits the dict class, so it can use the methods in the dict class

Create a Counter class

Import collectionsobj = collections. Counter ('abbccc') print (obj) # output: Counter ({'C': 3, 'A': 2, 'B': 2 })

Elements ()

Import collectionsobj = collections. counter ('abbccc') print (sorted (obj. elements () # output: ['A', 'A', 'B', 'B', 'C', 'C ', 'C'] for k in obj. elements (): # print all elements of obj print (k)

Most_common (specify a parameter n to list the first n elements. If no parameter is specified, all elements are listed)

Import collectionsobj = collections. Counter ('aabbbcccccc') print (obj. most_common (2) # output: [('C', 4), ('B', 3)]

Items (methods inherited from the dict class)

Import collectionsobj = collections. counter ('abbbcccccc') print (obj. items () for k, v in obj. items (): print (k, v) # output: dict_items ([('B', 3), ('C', 4), ('A ', 2)]) # B 3 # c 4 # a 2

Update (add element)

Import collectionsobj = collections. counter (['11', '22']) obj. update (['22', '55']) print (obj) # output: Counter ({'22': 2, '11': 1, '55 ': 1 })

 

 

Not complete...

 

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.