Python data type: Dual-ended queue
When it comes to container types, the first thing you think about is the list, and the list really solves most of the need, but when it comes to a fairly large amount of data in the list, the performance issue is especially important, and when the list is maliciously injected with an infinite amount of data, it can expose a security issue. A better alternative is: Collections.deque. For performance or security, the data size is sacrificed.
Deque queue Both sides remove or delete time complexity is O (1), and the list is O (n), the performance of the queue is better than the list
Brief introduction
Welcome to my public number: Python Goose Cross
Collections.deque Object (double-ended queue), which supports the addition of deleted elements from either end. deque is a thread-safe, memory-efficient queue that is designed to be appended and ejected from both ends very quickly.
Create a Deque object
deque () to create a Deque object
Optional Parameters :
- Iterable an iterative object, such as a list, a tuple
- MaxLen maximum length, exceeding the maximum length, will squeeze the previous element out
Example:
from collections import dequedq = deque([1,2,3,4]],maxlen=10)
Methods for Deque objects
dq.append (x) add X on the right side
>>>dq.append(5)>>>print(dq)deque([1, 2, 3,4,5])
dq.appendleft (x) add X on the left side
>>>dq.appendleft(0)>>>print(dq)deque([0,1,2,3,4,5])
dq.pop () popup element on the right side, if the queue has no elements, will error
>>>dq.pop()5
dq.popleft () popup element on left side, if the queue has no elements, will error
>>>dq.popleft()0
dq.extend (iterable) is similar to the extend of the list, extending the queue on the right, which is an iterative object
>>>dq.extend([5,6,7,8])
dq.extendleft (iterable) in the same vein
>>>dq.extendleft([5,6,7,8])
Dq.remove (value) removes the first value found and, if not found, causes indexerror
dq.remove(3)
dq.clear () empty queue
dq.clear()
rotate (n) if n>0, all elements move N to the right, otherwise left
dq.rotate(5)
If you learn something, remember to give me some praise, or you can follow my public number (Python goose Cross) for more interesting tutorials
Python data type: Double-ended queue deque-a data type with a higher performance than list