Several data structures in the python collection module (Counter, OrderedDict, namedtup)

Source: Internet
Author: User

Several data structures in the python collection module (Counter, OrderedDict, namedtup)

The collection module has several data structures that we may use.

Counter is a sub-class of the dictionary and is responsible for counting a dictionary. It supports + addition, subtraction, and common elements. | calculates the Union set.

 

Print ('counter type application') c = Counter ("dengjingdong") # c = Counter ({'N': 3, 'G': 3, 'D ': 2, 'I': 1, 'O': 1, 'E': 1, 'J': 1}) print ("Raw data:", c) print ("two elements at most:", c. most_common (2) # print ("Number of d:", c ['D']) of the most output elements # print (c. values () # print (sum (c. values () # print (sorted (c. elements () # Sort the data in the dictionary in the lexicographically ordered print ('\ n \ n ') "# Delete All d Elements del c ['D'] B = Counter (" dengxiaoxiao ") # Use the subtract function to delete elements. The number of elements can be negative. C. subtract (B) "You can add data B = Counter (" qinghuabeida ") c. update (B )"""
The OrderedDict type is an ordered dictionary, which is actually an order more than a common dictionary.

 

 

Print ('ordereddict-type application ') dic = {} dic ['a'] = 'A' dic ['B'] = 'B' dic ['C'] = 'C' odic = OrderedDict () odic ['a'] = 'A' odic ['B'] = 'B' odic ['C'] = 'C' print ('unordered dictionary: ', dic) print ('ordered dictionary: ', odic) print (' \ n \ n ')

Namedtup type. A dictionary-like tuples can be converted to dictionaries.

 

 

Print ('namedtup type application') deng = namedtuple ('deng', ['x', 'y']) I = deng (x = 11, y = 12) print ('I value:', I) print ('add two values: ', I [0] + I [1]) print ('add by attribute: ', I. x + I. y) m, n = iprint ('values similar to tuples: ', m, n) d = I. _ asdict () print ('convert to a dictionary: ', d)



 

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.