Python generator yield and send

Source: Internet
Author: User
Tags generator

Creating generators
1 #the first way to create a generator2 #use () to create a generator, and create a list if you use []3A = (x**2 forXinchRange (1, 5))4 #you can always generate new data through next until the last report exception, through the for traversal will not report the exception5 #You can also use a.__next__ ()6 Print(Next (a))#Output 17 Print(A.__next__())#Output 48 Print(Next (a))#Output 99 Ten #traversing the generator with for One  forIinchA: A     Print(i) -  - #the second way to create generators the defcreatenum (n): -      forIinchrange (n): -         yieldI**3 -  +  forIinchCreatenum (5): -     Print(i)

The generator's send usage generator.send (value)
1 #the generator's send usage generator.send (value)2 defTest ():3i = 14      whileI < 5:5temp =yieldI**26         Print(temp)7i + = 18 9t =Test ()Ten #The first run can only use Next or send (None) One Print(T.__next__()) A #the function of send is equivalent to keeping the generator running, and the passed parameter is the return value of yield (the value of temp in the program) - Print(T.send ("Hello World")) - Print(T.__next__())#equivalent to send (none) at this time temp = none

Python generator yield and send

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.