Python Collections Module

Source: Internet
Author: User

Collections Module

The Collections module provides several additional data types based on the built-in data types (dict, list, set, tuple): Chainmap, Counter, deque, Defaultdict, Namedtuple and Ordereddict and so on.

1.namedtuple: Generates a tuple subclass that can access the content of an element by using a name
2.deque: Double-ended queue to quickly append and eject objects from the other side
3.Counter: Counter, mainly used to count
4.OrderedDict: Ordered Dictionary
5.defaultdict: Dictionary with default values

Namedtuple

We know that we tuple can represent immutable collections, for example, two-dimensional coordinates of a point can be expressed as:

>>> p = (1, 2)

However, (1, 2) it is difficult to see that this tuple is used to denote a coordinate.

Defining a class is a fuss, and then namedtuple it comes in handy:

>>>From collectionsImport Namedtuple>>> Point= Namedtuple( ' point ' [ ' x '  ' y ' ]) >>> p = point (12>>> p.x1>>> P.y2          

namedtupleis a function that creates a custom object and specifies the tuple tuple number of elements and an element that can be referenced by a property rather than an index tuple .

In this way, we namedtuple can easily define a data type, it has the invariant of tuple, and can be referenced according to the attribute, the use is very convenient.

You can verify that the Point object being created is tuple a seed class:

>>> isinstance(p, Point)True>>> isinstance(p, tuple)True

Similarly, if you want to represent a circle with coordinates and radii, you can also use the namedtuple definition:

# namedtuple(‘名称‘, [属性list]):Circle = namedtuple(‘Circle‘, [‘x‘, ‘y‘, ‘r‘])
Deque

listwhen using stored data, accessing elements by index is very fast, but inserting and deleting elements is very slow, because list it is linear, and when the data is large, insertions and deletions are inefficient.

Deque is a two-way list for efficient insert and delete operations, suitable for queues and stacks:

>>>From collectionsImport deque>>> Q= Deque([A,' B ',C])>>> Q. append ( ' x ' >>> q.appendleft ( ' y ' >>> qdeque ( Span class= "token punctuation" >[ ' y '  ' B '  ' C '  ' x ' 

dequeIn addition to implementing the and outside of the list append() pop() , support appendleft() and popleft() , in this way, can be very efficient to add or remove elements to the head.

Defaultdict

dictwhen used, if the referenced key does not exist, it will be thrown KeyError . If you want to return a default value when the key does not exist, you can use defaultdict :

>>>From collectionsImport Defaultdict>>> DD= Defaultdict(Lambda ' n/a ' ) >>> dd[  ' Key1 ' ] =  ' abc ' >>> Dd[ ' Key1 ' ] # Key1 exists  ' abc ' >>> DD [ ' Key2 '  # key2 not present, return default value  ' n/a '         

Note The default value is returned by the calling function, and the function is passed in when the object is created defaultdict .

In addition to returning the default value when key does not exist, defaultdict the other behavior dict is exactly the same.

Ordereddict

dictwhen used, key is unordered. We were dict unable to determine the order of the keys when doing iterations.

If you want to keep the key in order, you can use OrderedDict :

>>>From collectionsImport Ordereddict>>> D= Dict([(A,1),(' B ',2),(C,3)])>>> D# Dict's key is unordered.{A:1,C:3,' B ':2}>>> OD= Ordereddict([(A,1),(' B ',2),(C,3)])>>> od # Ordereddict key is ordered Ordereddict ([  ' a ' 1  ( ' B ' 2 )  ( ' C ' 3) ])        /span>                

Note that OrderedDict the keys are arranged in the order in which they are inserted, not the key itself:

>>> OD= Ordereddict()>>> OD[' Z ']=1>>> OD[ ' y '  = 2>>> OD [ ' x '  = 3>> > Od.keys (# returns [ ' y '  ' x ' ]         

OrderedDictYou can implement a FIFO (first-in-one-out) dict, deleting the first added key when the capacity exceeds the limit:

From collectionsImport OrdereddictClassLastupdatedordereddict(ordereddict):Def__init__(Self, capacity): Super(lastupdatedordereddict, self). __init__() Self. _capacity= CapacityDef__setitem__(Self, key, value): ContainsKey=1If keyIn selfElse0If Len(Self)-ContainsKey>= Self. _capacity: Last= Self. Popitem(Last=False)Print' Remove: ', lastIf ContainsKeydel self[key print  else:  Print  (key< Span class= "token punctuation", Value.__setitem__ (self )  
Counter

Counteris a simple counter, for example, the number of statistical characters that appear:

>>>From collectionsImport Counter>>> C= Counter()>>>For CHInch' Programming ':... C[CH]= C[CH]+1...>>> Ccounter({' G ':2,' m ':2, ' R ' : 2  ' a ' : 1 ' I ' : 1 ' o ' : 1 ' P ' : 1})           

CounterActually also dict a subclass, the above results can be seen, the characters ‘g‘ , ‘m‘ , ‘r‘ each appeared two times, the other characters appear once.

Python Collections Module

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.