is placed in line and split into result. The return value of the Send () method is the value of the next yield statement. That is, the Send () method can pass a value to the yield expression, but its return value comes from the next yield expression, rather than the yield expression that receives the value passed by Send ().
If you want to use the Send () method to open the execution of the coprocessor, you must first send a none value, because there is no yield statement to accept the value,
.
If you want to print one one out, you can get the next return value of generator through the next () functionWhen there are no more elements, throw the stopiteration error.
def fib (max):
N, a, b = 0, 0, 1 while
n
'
IteratorsWe already know that there are several types of data that can be directly applied to the For loop:
A class is a set of data types, such as list, tuple, dict, set, str, etc.The class is generator, including generators and g
Generator
With a list build, you can generate a list directly. However, the list capacity is limited by memory constraints. If you create a list that contains 1 million elements, you only need to access a few of them, and the space is wasted.
If a list element can be calculated according to an algorithm, the subsequent elements are continually extrapolated during the loop so that there is no need to create a complete list, thus saving a lot of space. In Python, this side loop comput
execution. When the next () method of the generator is called, it will proceed exactly from where it left off.As you can see, the generator is similar to the concept of a co-process, pausing or suspending, and continuing execution from where the program left off.rows = [1, 2, 3, +]def cols (): yield , yield , 2 yield 1 for as in cols ()) x_product_pairs: print(pair)Operation Result:(1, About)(1,2)(1,1)(2, About)(2,2)(2,1)(3, About)(3,2)(3,1)( -, About)( -,2)( -,1)When the next ()
GeneratorIn Python, a function that uses yield is called a generator (generator).Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.In the process of calling the generator to run, the function pauses and saves all current run information each time the yield is encountered, returning the value of yield. and continue running from the current location the next time t
return).4. Use Send to wake upIn addition to using the next () function to wake the generator to continue execution, we can also use the Send () function to wake execution. One advantage of using the Send () function is that you can pass in an additional data to the breakpoint while waking. Example: When executing to yield, the function of the Gen function is temporarily saved, returning the value of I; Temp receives the next c.send ("Python"), send the value sent over, C.next () equivalent C.s
Example: When the program is finished, the last one yield. So after? continue in? __next__ () program will error okay? The builder says Let's take a look at this. Demand Company to jack jones order Purchase 10000 sleeve learn to serve made directly 10000 suit But the company does not have so many people now ah, you give me 10,000 sets I have no place to save Ah, very embarrassed,The perfect thing is that I use a set you give me a set of difference No. The
IteratorsEssentially, an iterator is an object that has a next () methodIterators can be created using the built-in iter method>>> i = iter ('abc')>>> i.next ()'a '>>> i.next ()'b'>>> i.next () ' C 'To create iterators for classes available __iter__ and next ()classFib (object):def __init__(self): SELF.A, self.b= 0, 1#Initialize two counters A, B def __iter__(self):returnSelf#The instance itself is an iterative object, so it returns itself defNext (self): SELF.A, self.b= self.b, SELF.A + s
: Print (Next (IT)) except stopiteration: sys.exit ()Execute the above procedure, the output result is as follows:1234GeneratorIn Python, a function that uses yield is called a generator (generator).Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.In the process of calling the generator to run, the function pauses and saves all current run in
is adjusted, encounters a return, and then carries on the line from __next__() yield語句 The last yield language that was returned.#!/usr/bin/env python3# -*- coding:utf-8 -*-def fib(max): n, a, b = 0, 0, 1 while n In the above Fib example, we constantly adjust the yield in the loop, and then we will keep going, and of course we have to set a condition for the loop to exit the loop, or it will produce an unlimited list.In the same way, after changing the function to generator, we basically
memory
To generate an iterator: # !/usr/bin/env python # -*-coding:utf-8-*- # Author:huanglinsheng hls = iter ([ 1,2,3,4,5]) print (hls.__next__ ()) print (HLS. __next__ ()) print (Hls. __next__ ()) print (Hls.__next__ ()) print (Hls. __next__ ()) Generator generatorDefinition: When a function call returns an iterator, the function is called the Generator (generator), and if the function contains the yield syntax, the function becomes the generatorCode:#!/usr/bin/
normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.In the process of calling the generator to run, the function pauses and saves all current run information each time the yield is encountered, returning the value of yield. and continue running from the current location the next time the next () method is executed.The following example uses yield to implement the Fibonacci
each value, get the last element, then call the stopiteration error, can be handled by snapping, a better way is to use a for loop, because generator is also an iterative object, No need to care about Stopiteration's mistakes.2. Using yield to implement the Fibonacci sequencedeffib (max): N, a, b= 0, 0, 1 whileN Max:yieldA, b## GeneratorA, B = B, A +B N+ = 1return "---done---"defMain (): G= FIB (6) forIinchg:Print(i[0],i[1])if __name__=='__main__': Main ()3. Using the generator to implement
simpler to understand that the generator is an iterator.In the process of calling the generator to run, the function pauses and saves all current run information each time the yield is encountered, returning the value of yield. and continue running from the current location the next time the next () method is executed.Yield keywordThe yield keyword and return usage are the same, as long as the function containing the yield keyword is a generator function, yield needs to be written inside the fu
))ForIt is only possible to iterate over objects to use the forWhen we come across a new variable, unsure if it can be used for a loop, we'll tell if it's iterative. for inch L: Pass = L.__iter__() iterator. __next__ ()Benefits of Iterators:A value from one of the container types will fetch all the values.Saves memory spaceIterators do not occupy a large chunk of memory in memory,Instead, each time the loop generates aEvery time next time you give me aGeneratorGenerator-Iteratordef generato
#Generator and co-process#A generator is a special iterator that also generates a sequence of values;#How do I define a generator? #method One: Use the yield keyword in the function; classCount_down (n): whileN>0:yieldN N-=1#Create a Builder objectc = Count_down (10) #__next__ () method call Builder;>> c.__next__() 10#the Builder object provides a close () method to avoid partial consumption;#that is, when you stop using the generator, the close () method is called automatically; cla
1. Iterators and generators
1.1 iteratorsBase iterator initialization and access
i = ITER (' abc ') print (i.__next__ ()) print (i.__next__ ()) print (
i.__next__ ()) for
I in ITER (' abc '):
Print (i)
For a class, __iter__ (self) and __next__ (self) are required. Also, use the raise stopiteration to stop the iterator.
Class Myiterator (object):
def __init__ (self):
self.a = 0
self.b = 1
def __iter__ (self):
return
You can create an environment that supports rapid application development (rapid application Development,rad) entirely with the code you have developed (and possibly some of the program modules from MSDN). But I think as a. NET developer, if you don't think about the existing Third-party code generators, you're cheating yourself and your company.
Using code GENERATOR,CG, you can get hundreds of, thousands of lines of code from a simple set of setting
Grunt-beginner Front-end automation tool:HTTP://WWW.IMOOC.COM/LEARN/30Grunt InstallationOfficial site: http://gruntjs.com/Installation Instructions:sudo npm install-g grunt-cliVerification aspect: GruntSee, that is Grunt has been installed
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.