How to use deque to retain the latest N elements in python (code)

不言
Release: 2018-10-11 14:12:41
forward
1859 people have browsed it

The content of this article is about the implementation method (code) of using deque to retain the latest N elements in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

1. Requirements

Make a limited number of historical records.

2. Solution

deque(maxlen=N), create a fixed-length queue, and when new records are added and the queue is full, the oldest record will be automatically removed. .

Code:

from collections import deque

q=deque(maxlen=3)

q.append(1)
q.append(2)
q.append(3)
print(q)
q.append(4)
print(q)
q.append(5)
print(q)
Copy after login

Result:

deque([1, 2, 3], maxlen=3)
deque([2, 3, 4], maxlen=3)
deque([3, 4, 5], maxlen=3)
Copy after login

If you do not specify the size of the queue, you will get an unbounded queue, and you can perform add and pop operations at both ends,

Code:

from collections import deque

q=deque()
q.append(1)
q.append(2)
q.append(3)
q.append(4)
print(q)
q.appendleft(5)
print(q)
print(q.pop())
print(q)
print(q.popleft())
print(q)
Copy after login

Result:

deque([1, 2, 3, 4])
deque([5, 1, 2, 3, 4])
4
deque([5, 1, 2, 3])
5
deque([1, 2, 3])
Copy after login

The above is the detailed content of How to use deque to retain the latest N elements in python (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template