Python Learning Diary Fifth article--collections series

Source: Internet
Author: User

First, counter (counter)

The counter (counter) returns the number of occurrences of each character in a sequence as a dictionary, a value of key, and a number of values

#!/usr/bin/env python#-*-coding:utf-8-*-#导入collections模块import collectionscounter_test = collections. Counter ("ASFAFJHADGKHJKGFJHGFJHAGHDG") print (counter_test) #返回值C: \python27\python27.exe d:/cto3/day6/coun_1. Pycounter ({' G ': 5, ' H ': 5, ' a ': 4, ' F ': 4, ' J ': 4, ' d ': 2, ' K ': 2, ' s ': 1})


1, the Counter method (dictionary method slightly)

Counter is a subclass of Dict, all of which have all the methods of the dictionary, and some of their own methods

#取前3位的返回值ret1 = Counter_test.most_common (3) print (RET1) ######### #result: [(' G ', 5), (' H ', 5), (' A ', 4)] #循环取计数器中的值for k,v In Counter_test.items (): Print (k,v) ######### #result:(' a ', 4) (' d ', 2) (' G ', 5) (' F ', 4) (' H ', 5) (' K ', 2) (' J ', 4) (' s ', 1) #up The date method, subtract method, updates with the removal of obj = collections. Counter ([11,22,33,22,]) print (obj) obj.update ([11,22,44]) print (obj) obj.subtract ([11,22,44]) print (obj) ########## Result:counter ({22:2, 33:1, 11:1}) Counter ({22:3, 11:2, 33:1, 44:1}) Counter ({22:2, 33:1, 11:1, 44:0})

Second, ordered dictionary (ordereddict)

An ordered dictionary (ordereddict) is a subclass of a dictionary that records the order in which elements are added, based on a dictionary

#导入collections模块import Collectionsdic = collections. Ordereddict () dic[' k1 '] = ' v1 ' dic[' k2 '] = ' v2 ' dic[' K3 '] = ' v3 ' Print (DIC) ######### #result: ordereddict ([' K1 ', ' v1 '), (' K2 ', ' V2 '), (' K3 ', ' v3 ')])

1, the method of the ordered dictionary (the method of the dictionary slightly)

#python3中新加入的方法, move the dictionary in order dic.move_to_end (' K1 ') print (DIC) ######### #result: ordereddict ([' K2 ', ' V2 '), (' K3 ', ' V3 '), ( ' K1 ', ' v1 ')]) #按照顺序, LIFO popup element (with return value) Dic.popitem () print (DIC) ######### #result: ordereddict ([' K1 ', ' v1 '), (' K2 ', ' V2 ')] #指定弹出的元素 (with return value) Dic.pop (' K2 ') print (DIC) ######### #result: ordereddict ([' K1 ', ' v1 '), (' K3 ', ' v3 ')]) #更新, The Update method dic.update ({' K1 ': ' New1 ', ' K4 ': ' v4 '}) print (DIC) ######### #result: ordereddict ([' K1 ', ' New1 '), (' K2 ', ' V2 '), ( ' K3 ', ' V3 '), (' K4 ', ' v4 ')])

Third, default dictionary (defaultdict)

The difference between a default dictionary and a dictionary is that you can set the type of its elements

#导入collections模块import collectionsmy_dict = collections.defaultdict (list) my_dict[' K1 '].append (' v1 ') print (my_dict) ######### #result:d efaultdict (<class ' list ', {' K1 ': [' v1 ']})

Example:

#  Exercise: Element classification #  has the following value collection  [11,22,33,44,55,66,77,88,99,90...],#  saves all values greater than  66  to the first key in the dictionary, Save the value less than  66  to the value of the second key. #  namely:  {' K1 ':  greater than 66 ,  ' K2 ':  is less than 66}1, do not use the default pointing to determine whether the dictionary has {' K1 ': []}all_list =  [11,22,33,44,55,66,77,88,99,90,]dic = {}for i in all_list:     if i > 66:        if  "K1"  in  Dic.keys ():             dic[' K1 '].append (i)          else:             dic[' K1 '] = [i,]    else:         if  "K2"  in dic.keys ():             dic[' K2 '].append (i) &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;ELSE:&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;       dic[' K2 '] = [i,]print (DIC) 2, default dictionary all_list = [ 11,22,33,44,55,66,77,88,99,90,]dic = collections.defaultdict (list) For i in all_list:     if i > 66:        dic[' K1 '. Append (i)     else:        dic[' K2 '].append (i) Print (DIC) ######### #result:d efaultdict (<class  ' list ' >, {' K2 ':  [11, 22, 33, 44,  55, 66],  ' K1 ':  [77, 88, 99, 90]})


Four, can be named Ganso (namedtuple)

The difference between namedtuple and tuples is that Namedtuple creates a class that contains a tuple and a specific method of its own

#导入collections模块import collections# creates a class that can be named tuples Mytupleclass = collections.namedtuple (' Mytupleclass ', [' X ', ' y ', ' z ') # Create object, obj object x=11,y=22,z=33obj = Mytupleclass (11,22,33) print (obj.x) print (OBJ.Y) print (obj.z) ######### #result : 112233


Five, queue

1. Bidirectional queue

#导入collections模块import  collectionsd = collections.deque (' Ghi ') Common methods: #右加入 >>>  D.append (' j ') #左加入 >>> d.appendleft (' F ') >>> ddeque ([' F ',  ' g ',  ' h ',  ' I ',  ' J ']) #右移除 (with a return value) >>> d.pop () ' J ' #左移除 (with a return value) >>> d.popleft () ' F ' >>>  ddeque ([' G ',  ' h ',  ' I ']) #队列可转换为列表 >>> list (d) [' G ',  ' h ',  ' I '] #右扩展 >> > d.extend (' JKL ') >>> ddeque ([' G ',  ' h ',  ' I ',  ' j ',  ' K ',  ' l ']) #左扩展 (reverse join queue) >>> d.extendleft (' abc ') >>> ddeque ([' C ',  ' B ',  ' a ',  ' G ',   ' h ',  ' I ',  ' j ',  ' K ',  ' l ']) #右轮换 >>> d.rotate (1) >>> ddeque ([ ' L ',  ' g ',  ' h ',  ' I ',  ' j ',  ' K ']) #左轮换 >>> d.rotate ( -1) >>>  Ddeque ([' G ',  ' h ',  ' I ',  ' j ',  ' K ',  ' l ']) #统计队列中元素出现的次数 >>> d.extend (' Ghijk ') ) >>> ddeque ([' G',  ' h ',  ' I ',  ' g ',  ' h ',  ' I ',  ' j ',  ' K ']) >>> d.count (' G ') clear >>> d.clear ()

2. One-way queue (FIFO)

Import queue# Create a one-way queue q = queue. Queue () #插入第一条数据q. Put (' 123 ') #插入第二条数据q. Put (' 456 ') #查看队列中有几条数据print (Q.qsize ()) #顺序取出第一条数据print (Q.get ()) ########## Result:2123


This article is from the "Linux Sailing" blog, make sure to keep this source http://jiayimeng.blog.51cto.com/10604001/1932093

Python Learning Diary Fifth article--collections series

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.