Python cookbook (data structure and algorithm) method for saving the last N elements, pythoncookbook

Source: Internet
Author: User

Python cookbook (data structure and algorithm) method for saving the last N elements, pythoncookbook

This example describes how to save the last N elements in Python. We will share this with you for your reference. The details are as follows:

Problem:We hope to make a limited history statistics for the last few records during iteration or other forms of processing.

Solution:Select collections. deque.

The following code performs a simple text match on a series of text lines. When a match is found, the current match line and the last N lines of text checked are output:

from collections import dequedef search(lines, pattern, history=5):  previous_lines = deque(maxlen=history)  for line in lines:    if pattern in line:      yield line, previous_lines    previous_lines.append(line)# Example use on a fileif __name__ == '__main__':  with open('somefile.txt') as f:    for line, prevlines in search(f, 'python', 5):      for pline in prevlines:        print(pline, end='')      print(line, end='')      print('-'*20)

Just like the code above, when writing code that searches for a record, a generator function containing the yield keyword is usually used, decouple the code that processes the search process from the code that uses the search results. For details about the generators, refer to the content related to the iterators and generators on this site.

deque(maxlen=N)Create a queue with a fixed length. When a new element is added and the queue is full, the oldest record is automatically removed:

>>> from collections import deque>>> q=deque(maxlen=3)>>> q.append(1)>>> q.append(2)>>> q.append(3)>>> qdeque([1, 2, 3], maxlen=3)>>> q.append(4)>>> qdeque([2, 3, 4], maxlen=3)>>> q.append(5)>>> qdeque([3, 4, 5], maxlen=3)>>>

Although you can manually perform such operations (append and del) on the list, the queue solution is much more elegant and faster.

If no queue length is specified, a non-boundary queue is obtained. You can add and pop-up operations at both ends:

>>> q=deque()>>> qdeque([])>>> q.append(1)>>> q.append(2)>>> q.append(3)>>> qdeque([1, 2, 3])>>> q.appendleft(4)>>> qdeque([4, 1, 2, 3])>>> q.pop()3>>> qdeque([4, 1, 2])>>> q.popleft()4>>> qdeque([1, 2])>>>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.