Several data structures in the Python collection module (Counter, Ordereddict, Namedtup)

Source: Internet
Author: User

There are several data structures in the collection module that we might be able to use.

Counter is a subclass of the dictionary that is responsible for counting a dictionary, supporting + addition-subtraction & seeking Common Elements | Seek and set

Print (' Counter type application ') c = Counter ("Dengjingdong") #c = Counter ({' n ': 3, ' G ': 3, ' d ': 2, ' I ': 1, ' O ': 1, ' E ': 1, ' J ': 1}) Prin T ("raw Data:", c) print ("Up to two elements:", C.most_common (2)) #输出数量最多的元素print ("Number of D:", c[' d ')) #输出d的个数print (C.values ()) # The value list of the output dictionary, print (SUM (c.values ())) #输出总字符数print (sorted (c.elements ())) #将字典中的数据, sort print by dictionary order (' \ n ') "" #删除所有d元素del c[' d '] b = Counter ("Dengxiaoxiao") #通过subtract函数删除元素, the number of elements can become negative. C.subtract (b) "" "" "" can add data B = Counter ("Qinghuabeida") C.update (b) "" "
The ordereddict type is an ordered dictionary, which is actually a more sequential order than a normal dictionary.

Print (' ordereddict type of 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 ')

Namedtup type, a dictionary-like tuple that can be converted to a dictionary

Print (' Namedtup type application ') Deng = namedtuple (' Deng ', [' X ', ' y ']) i = Deng (x = 11,y = y) print (' I's value: ', i) print (' Add two values: ', i[0]+i [1]) Print (' Add by attribute: ', i.x+i.y) m,n = iprint (' Assignment to tuple: ', m,n) ' d = i._asdict () print (' Convert to a dictionary: ', D)



Several data structures in the Python collection module (Counter, Ordereddict, Namedtup)

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.