10-4 Generators

Source: Internet
Author: User

Generator

The function that you write yourself

A simple generator function

As long as the __next__ () function and _iter__ () are included in the generator

Def genetator ():    print (1)    return ' a ' ret = Genetator () print (ret) Result: 1a
As long as the function containing the Yeild keyword is a generator function and is not shared with return and needs to be written inside the function
Def genetator ():    print (1)    yield ' A ' # generator function: After execution you get a build as a return value ret = Genetator () print (ret) #结果: <generator Object Genetator at 0x0225dcc0>print (ret.__next__ ()) # Result: # aret.__iter__ ()

Def Wahaha (): For    i in range:        yield ' Wahaha%s '%ig=wahaha () #只拿前五个, with count count = 0for k in g:    count + = 1    Print (k)    if Count > 5:        break# can take another value print at any time (' Ooooo ', g.__next__ ())
Each generation of generators is unrelated to each other, and each execution

 

Example of listening file input (generator)
# Listen for input to the file
def tail (filename):    f = open (filename,encoding= ' utf-8 ') while    True: line        = F.readline ()        if Line.strip ():            print (' * * * ', line.strip ()) tail (' info ')
#监听文件的输入, and filter the content
def tail (filename):    f = open (filename,encoding= ' utf-8 ') while    True: line        = F.readline ()        if Line.strip ():            yield Line.strip () g = tail (' info ') for I in G: "    if ' python ' in I:        print (' ****** ', I, ' ~ ~ ~ ~ ')" C18/>if ' www ' in I:        print (' ****** ', I, '!!!! ')

  

10-4 Generators

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.