This article will learn about another Python built-in module, collections, for more information, see: Python Learning Guide
Collections is a python built-in collection module that provides a number of useful collection classes.
Namedtuple
We know that we tuple
can represent immutable collections, for example, the two-dimensional left side of a point can be represented as:
>>>= (12)
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 nametuple
it comes in handy:
>>>fromimport namedtuple>>>= namedtuple('Point', ['x''y'])>>>= Point(12)>>> p.x1>>>p.y2
namedtuple
is 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
.
You can validate Point
a seed class when creating an object tuple
:
>>>isinstance(p, Point)True>>>isinstancetuple)True
Similarly, if you want to use coordinates and radii to represent a garden, you can also use the namedtuple
definition:
# namedtuple("名称", [属性list])= namedtuple("Circle", ['x''y''r'])
Deque
list
when 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 queue for efficient insert and delete operations, suitable for queues and stacks:
>>>fromimport deque>>>= deque(['a''b''c'])>>>q.append('x')>>>q.appendleft('y')>>>qdeque(['y''a''b''c''x'])
deque
In 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
dict
when 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
:
>>>fromimport defaultdict>>>= defaultdict(lambda:'N/A')>>>dd['key1'='abc'>>>dd['key1']'abc'>>>dd['key2']'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
dict
when 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
:
>>> fromCollectionsImportOrdereddict>>>D= Dict([(' A ',1), (' B ',2), (' C ',3)])>>>D#dict的Key是无序的{' A ':1,' C ':3,' B ':3}>>>Od=Ordereddict ([(' A ',1), (' B ',2), (' C ',3)])>>>Odordereddict ([(' A ',1), (' B ',2), (' C ',3)])
Note that OrderedDict
the keys are arranged in the order in which they are inserted, not the key itself:
>>>= OrderedDict()>>>od['z'=1>>>od['y'=2>>>od['x'=3>>>list(od.keys()) #按照插入的Key的顺序返回['z''y''x']
OrderedDict
You can implement a FIFO (first-in-one-out) dict, deleting the first added key when the capacity exceeds the limit:
fromCollectionsImportOrdereddictclassLastupdatedordereddict (ordereddict):def __init__( Self, capacity):Super(Lastupdatedordereddict, Self).__init__() Self. _capacity=Capacitydef__SEITEM__ ( Self, key, value): ContainsKey= 1 ifKeyinch Self Else 0 if Len( Self)-ContainsKey>= Self. _capacity:last= Self. Popitem (Last=False)Print("Remove:", last)ifContainsKey: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 statistical string:
>>> from collections import counter>>> c = Counter () >>> for Ch Span class= "OP" >in ' programming ' : c[ch] = c[ch] + 1 >>> ccounter ({ : 2 , ' m ' : 2 , : Span class= "DV" >2 , ' a ' : 1 , : Span class= "DV" >1 , ' o ' : 1 , ' n ' : Span class= "DV" >1 , ' P ' : 1 })
Counter
Actually also dict
a subclass, the above results can be seen, the characters g
, m
r
each appeared two times, the other characters appeared once.
Summary
collections
The module provides some useful collection classes that can be selected as needed.
Python self-built collections module