Python Learning Diary collections Module

Keywords: Python

Based on the built-in functions (dict, list, set, tuple), the collections module also provides several other data types: Counter, deque, defaultdict, namedtuple, OrdereDict, etc.

1.namedtuple

Role: Used to generate a tuple that can access element content by name

If we want to represent a point, we can express it this way, but when we use it, we can hardly see that this tuple is used to represent a coordinate.

p = (1,2)

So we call namedtuple to solve this problem.

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)

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)

Represents the properties of a circle:

import collections
Circle = collections.namedtuple('Circle',['r','d','s','l'])

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's start with a queue quque()

Characteristics of queues: First in first out (FIFO)

import queue
i = 1
q = queue.Queue()
q.put(5)
q.put(6)
q.put(-5)
print(q)          #<queue.Queue object at 0x0000000002082EB8>
print(q.qsize())  #3    The entire queue length is 3
print(q.get())    #5
print(q.get())    #6
print(q.get())    #-5
print(q.get())    #Blocking because the entire queue has only three elements,When all three elements are removed, no new elements can be removed.,The program waits for the user to give it a value.

deque() double-ended queue, both sides of the head can be retrieved and stored

from collections import deque
dq = deque([5,6])
dq.append('a')              #Place data from the back
dq.appendleft('b')          #Place data from the front
dq.insert(1,'c')            #Add under 1 Index'c',The element in situ moves one bit backward
print(dq)                   #deque(['b', 'c', 5, 6, 'a'])
print(dq.pop())             #a      Pop back an element'a'
print(dq.popleft())         #b      Pop an element forward'b'

The advantage of using queues is that they can efficiently insert and delete bidirectional lists, which are suitable for queues and stacks.

And we use list, although access to elements is fast, but we insert or delete an element will be much slower, when the amount of data is large, insert and delete efficiency will be very low.

3.OrderedDoct

Ordered dictionary

Posted by ready2drum on Sun, 06 Oct 2019 22:45:43 -0700