The collections module in Python

Source: Internet
Author: User
Tags iterable

This module implements a number of classes, which are very flexible. Can be used to replace Python's built-in dict, list, tuple, set type. And some features are not available for these built-in types.

On the network to find some information, focusing on the collections module deque, Defaultdict, Counter class


1. Class Deque
Similar to Python's built-in list, but it's a two-way list. Can be manipulated at any end

Help (Collections.deque)

Class Deque (__builtin__.object)
Deque ([iterable[, MaxLen]])--Deque Object

The deque parameter should be a iterable.


Example:

In [1]: import collectionsin [2]: d = collections.deque (' abcdef ') In [3 ]: print ddeque ([' A ',  ' B ',  ' C ',  ' d ',  ' e ',  ' F ']) in [4]: d.append (' MM ')           #追加元素In  [5]: print ddeque ([' A ',  ' B ',  ' C ',  ' d ',  ' e ',  ' f ',  ' mm ']) in [6]: d.appendleft (' GG ')     #从左追加元素In  [7]: print ddeque ([' GG ',  ' a ',  ' B ',  ' C ',  ' d ',  ' e ',  ' f ',   ' mm ']) In [8]: d.pop ()     # pop  one element out[8]:  ' mm ' in [9]:  print ddeque ([' GG ',  ' a ',  ' B ',  ' C ',  ' d ',  ' e ',  ' F ']) in [10]:  D.popleft ()   #从左pop   An element out[10]:  ' GG ' in [11]: print ddeque ([' A ',  ' B ',  ' C ',  ' d ',  ' e ',  ' F ']) in [12]: d.extend (' xyz ')     #扩展In  [13]:  Print ddEque ([' A ',  ' B ',  ' C ',  ' d ',  ' e ',  ' F ',  ' x ',  ' y ',  ' z ']) in [14]:  D.extendleft (' 123 ')    #左扩展In  [15]: print ddeque ([' 3 ',  ' 2 ',  ' 1 ',  ' a ',   ' B ',  ' C ',  ' d ',  ' e ',  ' F ',  ' x ',  ' y ',  ' z ']) in [16]: d.reverse ( )   #反转In  [17]: print ddeque ([' Z ',  ' y ',  ' x ',  ' F ',  ' e ',  ' d ',  ' C ',  ' B ',  ' A ',  ' 1 ',  ' 2 ',  ' 3 ']) in [22]: d.extend (' 1111 ') in [23]:  D.count (' 1 ')        #统计一个元素的个数Out [23]: 5in [24]: print ddeque ( [' Z ',  ' y ',  ' x ',  ' F ',  ' e ',  ' d ',  ' C ',  ' B ',  ' A ',  ' 1 ',  ' 2 ',   ' 3 ',  ' 1 ',  ' 1 ',  ' 1 ',  ' 1 ']) in [27]: d.rotate (2)    #右旋转In  [28]:  print ddeque ([' 1 ',  ' 1 ',  ' z ',  ' y ',  ' x ',  ' F ',  ' e ',  ' d ',  ' C ',   ' B ',  ' a ',   ' 1 ',  ' 2 ',  ' 3 ',  ' 1 ',  ' 1 ']) in [29]: d.rotate ( -2)   #左旋转In  [30]: print  ddeque ([' Z ',  ' y ',  ' x ',  ' F ',  ' e ',  ' d ',  ' C ',  ' B ',  ' A ',  ' 1 ',   ' 2 ',  ' 3 ',  ' 1 ',  ' 1 ',  ' 1 ',  ' 1 ']) in [31]: d.clear ()   #清空In  [32] :  print ddeque ([])


In addition, a maxlen parameter is found in the Deque function. The main limitation is the size of this two-way list

In [the]: D = collections.deque (xrange), 5) in [+]: Print Ddeque ([5, 6, 7, 8, 9], maxlen=5) in [36]:


2. Class Defaultdict


Python's built-in Dict type has a SetDefault method, which means. Gets the value corresponding to the key in a dict. If this key does not exist in the dict, then in this dict set key, the key corresponding to the value of defaultdict set the corresponding values

Example:

in [+]: D = {' name ': ' God ', ' age ': 28}in []: D.setdefault (' name ') # This key exists in Dict and therefore returns the corresponding valueout[52]: ' God ' in [48]: D.setdefault (' Test ') # This key does not exist in Dict, so it is set to Dict, no value is specified, value is Nonein [+]: dout[49]: {' age ': ' ' Name ': ' G Od ', ' Test ': none}in [[]: D.setdefault (' test2 ', ' Test2value ') # This key does not exist in Dict, so it is set to Dict, specifying value as "Test2value" Ou T[50]: ' Test2value ' in [Wuyi]: dout[51]: {' age ': +, ' Name ': ' God ', ' Test ': None, ' test2 ': ' Test2value '}


The class defaultdict is similar to the SetDefault function in Dict. It just sets the default value when it initializes the Dict.

Example:

#! /usr/bin/env pythonimport collectionsdef default_factory (): Return "Defualt value" #在dict存在一个d [' foo '] = ' bar ' value. If you get a key that does not exist in Dict, the return value of #则返回default_factory function d = collections.defaultdict (default_factory,foo= ' bar ') print ' d: ', dprint "Foo=>", D.get (' foo ') print "foo=>", d[' foo ']print "var=>", d[' bar ']print ' * ' * 20# defined dict, if key does not exist in Dict, Then put this key in Dict, # and assign this key to LISTD = Collections.defaultdict (list) print ' d: ', Dprint ' foo=> ', D.get (' foo ') print foo= > ", d[' foo ']print" var=> ", d[' bar]


The results of the implementation are as follows:

D:defaultdict (<function default_factory at 0x7f230849e8c0>, {' foo ': ' Bar '}) foo=> barfoo=> barvar=> Defualt value********************d:defaultdict (<type ' list ';, {}) foo=> nonefoo=> []var=> []


3. Class Counter

I feel counter. This class compares cattle, which accepts several types of parameters and returns a Dict


>>> C = Counter () # A new, empty Counter
>>> C = Counter (' Gallahad ') # A new Counter from an iterable
>>> C = Counter ({' A ': 4, ' B ': 2}) # A new Counter from a mapping
>>> C = Counter (a=4, b=2) # A new Counter from keyword args

Look at all the results:

In [1]: Import Collectionsin [2]: c = collections. Counter () in [3]: Print Ccounter () in [4]: c = collections. Counter (' ABCDEFG ') in [5]: Print Ccounter ({' A ': 1, ' C ': 1, ' B ': 1, ' E ': 1, ' d ': 1, ' G ': 1, ' F ': 1}) in [6]: c = collections. Counter ({' A ': 4, ' B ': 2}) in [7]: Print Ccounter ({' A ': 4, ' B ': 2}) in [8]: c = collections. Counter (a=4, b=2) in [9]: Print Ccounter ({' A ': 4, ' B ': 2})

So what is the structure of this return dict? In its own words, it's like this.

Elements is stored as dictionary keys and their counts are stored as dictionary values


The following is a few examples of its own use:

In [ten]: c = collections. Counter (' Abcdeabcdabcaba ') in [all]: print Ccounter ({' A ': 5, ' B ': 4, ' C ': 3, ' d ': 2, ' E ': 1}) in []: C.most_common (3) # Display Number of three elements out[13]: [(' A ', 5), (' B ', 4), (' C ', 3)]in []: Sorted (c) # filter weight out[14]: [' A ', ' B ', ' C ', ' d ', ' E ']in []: D = Collections. Counter (' Simsalabim ') in [+]: c.update (d) # update d this Counter to C in [+]: Print Ccounter ({' A ': 7, ' B ': 5, ' C ': 3, ' d ': 2, ' I ': 2, ' m ': 2, ' s ': 2, ' E ': 1, ' L ': 1}

In short, the Counter class corresponding to the example, you can refer to the Dict method to operate. In the example above, you can use Help (c) to get the appropriate information.

This article is from the "Learning Notes" blog, so be sure to keep this source http://unixman.blog.51cto.com/10163040/1651985

The collections module in Python

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.