# A tutorial using Python's built-in modules collections

Source: Internet
Author: User

This article mainly introduces the use of Python's built-in module collections tutorial, the sample code based on the python2.x version, the need for friends can refer to the

Collections is a collection module built in Python that provides a number of useful collection classes.

Namedtuple

We know that tuple can represent invariant sets, for example, the two-dimensional coordinates of a point can be expressed as:

?

 1 >>> p = (1, 2)

But, seeing (1, 2), it's hard to see that this tuple is used to represent a coordinate.

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

?

 1 2 3 4 5 6 7 >>> from collections import namedtuple >>> point = namedtuple (' point ', [' X ', ' y ']) >>> p = poin T (1, 2) >>> p.x 1 >>> p.y 2

Namedtuple is a function that creates a custom tuple object and sets the number of tuple elements, and can refer to an element of tuple with attributes rather than indexes.

In this way, we can easily define a data type with namedtuple, it has the invariance of tuple, and can be referenced by attributes, very convenient to use.

You can verify that the point object you created is a seed class for tuple:

?

 1 2 3 4 >>> isinstance (P, point) True >>> isinstance (p, tuple) True

Similarly, if you want to represent a circle with coordinates and radii, you can also use Namedtuple to define:

?

 1 2 # namedtuple (' name ', [Property list]): Circle = namedtuple (' Circle ', [' X ', ' y ', ' r '])

Deque

When you use the list to store data, the elements are quickly accessed by index, but the insertion and deletion elements are slow because the list is linear and the insertion and deletion efficiency is low when the data is large.

Deque is a two-way list of inserts and deletions for efficient implementation, and is suitable for queues and stacks:

?

 1 2 3 4 5 6 >>> from collections import deque >>> q = deque ([' A ', ' B ', ' C ']) >>> q.append (' x ') >>> Q.appendleft (' y ') >>> q deque ([' Y ', ' A ', ' B ', ' C ', ' X '])

In addition to implementing the Append () and pop () of the list, Deque supports Appendleft () and Popleft (), which enables you to add or remove elements to the head very efficiently.

Defaultdict

When using Dict, if the referenced key does not exist, a keyerror is thrown. If you want the key not to exist, return a default value, and you can use Defaultdict:

?

 1 2 3 4 5 6 7 >>> from collections import defaultdict >>> dd = defaultdict (lambda: ' N/a ') >>> dd[' key1 '] = ' A BC ' >>> dd[' Key1 '] # Key1 exists ' abc ' >>> dd[' Key2 '] # Key2 does not exist, return default ' N/a '

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

In addition to returning the default value when the key does not exist, Defaultdict's other behavior is identical to that of Dict.

Ordereddict

When using Dict, the key is unordered. We cannot determine the order of keys when iterating over Dict.

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

?

 1 2 3 4 5 6 7 >>> from collections import ordereddict >>> d = dict ([(' A ', 1), (' B ', 2), (' C ', 3)]) >>> D # di The key of the CT is unordered {' A ': 1, ' C ': 3, ' B ': 2} >>> od = ordereddict ([(' A ', 1), (' B ', 2), (' C ' and 3]] >>> OD # ordere The key of Ddict is ordered ordereddict ([(' A ', 1), (' B ', 2), (' C ', 3)]

Note that the Ordereddict key is sorted in the order in which it was inserted, not by the key itself:

?

 1 2 3 4 5 6 >>> od = ordereddict () >>> od[' z '] = 1 >>> od[' y '] = 2 >>> od[' x '] = 3 >>> od . Keys () # are returned in the order of the inserted key [' Z ', ' y ', ' x ']

Ordereddict can implement a FIFO (first-in first Out) Dict, when the capacity exceeds the limit, first delete the first added key:

?

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 From collections Import Ordereddict class Lastupdatedordereddict (ordereddict): Def __init__ (self, capacity): Super (Las Tupdatedordereddict, self). __init__ () self._capacity = Capacity def __setitem__ (self, Key, value): containskey = 1 if ke Y in self else 0 if Len (self)-containskey >= self._capacity:last = Self.popitem (last=false) print ' Remove: ', last if Containskey:del Self[key] print ' Set: ', (key, value) Else:print ' Add: ', (key, value) ordereddict.__setitem__ (self, key, Value

Counter

Counter is a simple counter, for example, the number of occurrences of a statistic character:

?

 1 2 3 4 5 6 7 >>> from collections import Counter >>> c = Counter () >>> for-ch in ' programming ': ... c[ch] = C[CH] + 1 ... >>> c Counter ({' G ': 2, ' m ': 2, ' R ': 2, ' a ': 1, ' I ': 1, ' O ': 1, ' n ': 1, ' P ': 1})

Counter is actually a subclass of Dict, and the result shows that the characters ' G ', ' m ', ' r ' appear two times, and the other characters appear once.

Summary

The Collections module provides a number of useful collection classes that can be selected on demand.

Related Keywords:
Related Article

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD