Python basics: Every step with the yield keyword function call

Source: Internet
Author: User

1 #-*-coding:utf-8-*-2 __author__='Administrator'3 4  fromCollectionsImportdeque5 6 defSearch (lines, pattern, history=5):7Previons_line = Deque (maxlen=History )8      forLineinchlines:9         ifPatterninchLine :Ten             yieldLine , Previons_line One Previons_line.append (line) A  -  - #Example use on a file the if __name__=='__main__': -With open ('. \somefile.txt') as F: -          forLine, PrevlinesinchSearch (F,'python', 5): -              forPlineinchPrevlines: +                 Print(pline) -             Print(Line,"end= "") +             Print('-'*20) A            at      
View Code

Contents of the Somefile.txt file:

The first call to the search () function returns to the main function when it runs to yield line,previons_line, that is, Previons_line is empty, which executes the output after the main function, and the second call to the search () function, directly from the Previons_ Line.append (line) starts running until the yield line,previons_line is run back to the main function. And so on, so the last line in Somefile.txt, "Python is end." Will not be added to the previons_line.

Python basics: Every step with the yield keyword function call

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.