Python_collections_counter Counter Section function introduction

Source: Internet
Author: User

Counter (): is a dictionary supplement that is used to conveniently count and inherit the dictionary

Import= collections. Counter ('yigbavfsdcfdsfdsd')print(obj)
Result: Counter ({'D': 4,'F': 3,'s': 3,'y': 1,'I': 1,'g': 1,'b': 1,'a': 1,'v': 1,'C': 1})

X.most_common (): Returns the first n elements in descending order of the counter count, in the form of a list

Import= collections. Counter ('yigbavfsdcfdsfdsd')print(obj)  Print(Obj.most_common (4))
Result: Counter ({'D': 4,'F': 3,'s': 3,'y': 1,'I': 1,'g': 1,'b': 1,'a': 1,'v': 1,'C': 1}) [('D', 4), ('F', 3), ('s', 3), ('y', 1)]

X.element (): Returns an element according to the count of counter

Import= collections. Counter ('yigbavfsdcfdsfdsd') for in Obj.elements ():    print(k)
Results: YIGBAVFFFSSSDDDDC

X.update (): Update counter, add or modify on original basis

X.subtract (): Reduces the element on the basis of the original counter, and does not count as negative

ImportCollectionsobj= Collections. Counter ([' -','We',' -',' One'])Print(obj) obj.update (['Zhao',' One','QQ',' One', ])Print(obj) obj.subtract (['Zhao',' One','QQ','Lihao', ])Print(obj)
Results:

Counter ({' $ ': 2, ' we ': 1, ' 11 ': 1})

Counter ({' One ': 3, ' $ ': 2, ' we ': 1, ' Zhao ': 1, ' QQ ': 1})

Counter ({' $ ': 2, ' one ': 2, ' we ': 1, ' Zhao ': 0, ' QQ ': 0, ' Lihao ':-1})

Python_collections_counter Counter Section function introduction

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.