Python--Counter class

Source: Internet
Author: User
Tags iterable

Python--Counter class


I know you'll come, so I'll wait

Reference

Official documents

Class collections. Counter ([iterable-or-mapping])

Counter is integrated into the Dict class, so you can also use the dictionary method, which returns a collection of Counter objects with element key and number of elements as value

>>> from collections import Counter>>> s = "hello pinsily">>> d = Counter(s)>>> dCounter({‘l‘: 3, ‘i‘: 2, ‘h‘: 1, ‘e‘: 1, ‘o‘: 1, ‘ ‘: 1, ‘p‘: 1, ‘n‘: 1, ‘s‘: 1, ‘y‘: 1})
Elements ()

Returns an iterator

>>> d.elements()<itertools.chain object at 0x0000019AC812BBA8># 可以进行打印和排序>>> for i in d.elements():...     print(i)...
Most_common (N)

Returns the highest number of first n elements

>>> d.most_common(3)[(‘l‘, 3), (‘i‘, 2), (‘h‘, 1)]
Subtract ([iterable-or-mapping])

Equivalent to subtraction, Counter that call this method will be overwritten.

>>> c = Counter(a=4, b=2, c=0, d=-2)>>> d = Counter(a=1, b=2, c=3, d=4)>>> c.subtract(d)>>> cCounter({‘a‘: 3, ‘b‘: 0, ‘c‘: -3, ‘d‘: -6})>>> dCounter({‘d‘: 4, ‘c‘: 3, ‘b‘: 2, ‘a‘: 1})
Summarize

When you need to count a large amount of data in a list, you can use Counter directly instead of creating a new dictionary to count

Python--Counter class

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.