On the basis of built-in functions (dict, list, set, tuple) on, collections module also offers several other data types: Counter, deque, defaultdict, namedtuple and the like OrdereDict
1.namedtuple
Role: used to generate a name can be used to access content of the element tuple
If you want to express a point, we can say so, but when we use is difficult to see this tuple is used to represent a coordinate
p = (1,2)
So we call namedtuple to solve this problem
It represents a point in two dimensions:
import collections Point = collections.namedtuple('Point',['x','y']) print(Point) #<class '__main__.Point'> p = Point(1,2) print(p.x) #1 print(p.y) #2 print(p) #Point(x=1, y=2)
It represents a point in three dimensions:
import collections Point = collections.namedtuple('Point',['x','y','z']) print(Point) #<class '__main__.Point'> p = Point(1,2,3) print(p.x) #1 print(p.y) #2 print(p.z) #3 print(p) #Point(x=1, y=2, z=3)
It represents the properties of a circle:
import collections Circle = collections.namedtuple('Circle',['r','d','s','l'])
He represents a playing card:
Import Collections Card = collections.namedtuple ( ' Card ' , [ ' c_class ' , ' c_num ' ]) C = Card ( ' block ' , ' . 4 ' ) Print (c.c_class) # block Print (c.c_num) # . 4 Print (C) # Card (c_class = 'block', c_num = '4')
2.deque ()
Let me talk a queue here quque ()
Queue characteristics: First In First Out (FIFO)
Import Queue I =. 1 Q = Queue.Queue () q.put ( . 5 ) q.put ( . 6 ) q.put ( -5 ) Print (Q) # <Object Queue.Queue AT 0x0000000002082EB8> Print (q.qsize ( )) # 3 the entire length of the queue 3 Print (q.get ()) # . 5 Print (q.get ()) # . 6 Print (q.get ()) # -5 Print (q.get ()) # obstruction because the entire cohort only three elements, when taken out after all three elements could take no new elements, the program will have been waiting for the user to give it a value
the deque () deque, both sides of the head can fetch and store
from Collections Import the deque DQ = the deque ([5,6 ]) dq.append ( ' A ' ) # reproducing data from behind dq.appendleft ( ' B ' ) # front discharge data dq.insert (. 1, ' C ' ) # Add 'c' at the index 1, the element moves back in the original position a Print (DQ) # the deque ([ 'B', 'c',. 5,. 6, 'a']) Print (DQ. pOP ()) # a pop-up element a rearwardly 'a' Print (dq.popleft ()) # B a pop forwardly element 'b'
Benefits of using queues is that two-way list can efficiently insert and delete operations, suitable for queues and stacks
And we use the list, although access to the elements fast but we want to insert or delete an element will be much slower, when the large amount of data, insert and delete efficiency will be very low
3.OrderedDoct
Ordered dictionary