The collections module in Python provides a number of useful collection classes, where the deque can be described as a list of enhanced editions.
Deque basically have all the list methods:
From collections Import deque
q=deque ([1,2,3])
q.append (1)
print (q)
q.extend ([4,5])
print (q)
q.pop ()
print (q)
Run Result:
Deque ([1, 2, 3, 1])
deque ([1, 2, 3, 1, 4, 5])
deque ([1, 2, 3, 1, 4])
Deque (of course) is as iterable as a list:
M=map (str,q)
print (list (m))
The map function receives two parameters, the first is a function, and the second is the Iterable object. It passes the Iterable member to the function in turn, returning a map object. (Learn more: Http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014317852443934a86aa5bb5ea47fbbd5f35282b331335000)
The results are as follows, it is easy to convert a digital queue into a corresponding string list
[' 1 ', ' 2 ', ' 3 ', ' 1 ', ' 4 ']
In addition to the functions that these lists can satisfy, Deque has two "black magic" which is not available in the list.
Skill One: Limit the number of members
When a queue is created, the number of members is restricted by MaxLen, and the old member is automatically deleted when the new member joins and the queue is full.
From collections Import deque
q=deque ([1,2,3],maxlen=3)
q.append (4)
print (q)
The preceding code runs the result:
Deque ([2, 3, 4], maxlen=3)
Skill Two: Operation queue Head
When using the list, the Append and Pop methods are only for the end of the list, and if you want to add or remove members at the beginning of the queue, you need deque Appendleft and Popleft methods:
From collections Import deque
q=deque ([1,2,3])
q.appendleft (4)
Q.appendleft (5)
print (q)
Q.popleft ()
print (q)
The results of the above code run are obvious:
Deque ([5, 4, 1, 2, 3])
deque ([4, 1, 2, 3])