Example analysis of Python generator generator usage

Source: Internet
Author: User
Tags generator generator generator

This example describes the Python builder generator usage. Share to everyone for your reference. Specifically as follows:

With yield, you can have a function generate a sequence of results, not just a value

For example:

?

1 2 3 4 5 6 7 8 9 10 11 12-13 def countdown (n): print "Counting Down" while N>0:yield n #生成一个n值 n-=1 >>> C = Countdown (5) >>> C.N EXT () Counting down 5 >>> c.next () 4 >>> c.next () 3

Next () calls the builder function until the next yield statement, at which point next () passes the return value to yield. And the function pauses execution. When you call the next time (), the function continues to execute the statement after yield. This procedure continues to execute until the function returns.

Instead of manually calling next () like the above, you use a for loop, for example:

?

1 2 3 4 5 6 7 8 9 >>> for I in Countdown (5): ... print I. Counting down 5 4 3 2 1

Next (), the return value of Send () is the argument after yield, and the difference between send () and next () is that send () is an expression that sends an argument to (yield N) as its return value to M, and next () is to send a none to (yield N) The expression, which needs to be distinguished, is the return value of the call to next (), send (), and the return value of (yield N), which is not the same. See the output can be distinguished.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16-17 def h (N): while n>0:m = (yield n) print "M are" +str (m) n-=1 print "N is" +str (n) >>> p= H (5) >>> P.N Ext () 5 >>> P.next () m is None-4 4 >>> p.send ("test") m is test n is 3 3

I hope this article will help you with your Python programming.

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.