"Python Cookbook" "Data Structure and algorithm" 3. Save the last n elements

Source: Internet
Author: User

Question: Want to make a limited history of the last few records during iterations or other forms of processing

Solution: Select Collections.deque.

The following code makes a simple text-matching operation on a series of lines of text, outputting the current matching row and the last checked n-line text when a match is found:

 fromCollectionsImportdequedefSearch (lines, pattern, history=5): Previous_lines= Deque (maxlen=History ) forLineinchlines:ifPatterninchLine :yieldLine , Previous_lines previous_lines.append (line)#Example use on a fileif __name__=='__main__': With open ('Somefile.txt') as F: forLine, PrevlinesinchSearch (F,'python', 5):             forPlineinchPrevlines:Print(Pline, end="')            Print(Line, end="')            Print('-'*20)

As in the code above, when you write code that searches for a record, you typically use a generator function that contains the yield keyword to decouple the code that processes the search from the code that uses the search results. Specific generators are described in the "Iterators and Generators" section 3.

Deque (maxlen=n) creates a fixed-length queue that automatically removes the oldest record when a new element is added and the queue is full:

 from 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 this can be done manually on the list (append, Del), this solution for the queue is much more elegant and runs much faster.

If you do not specify a queue length, you get a queue with no bounds, and you can perform add and eject 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 ])>>>

"Python Cookbook" "Data Structure and algorithm" 3. Save the last n elements

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.