1, yield: used to return data. After the program executes to yield, return the result, remember the current state, suspend execution, and the next time, according to the previous state, return to the next result, remember the new state, suspend execution ,...
To put it simply, it is called once, spit out 1 data, then called again, spit out the second data, and called again, spit out the third..., when the model is trained, each batch of data is spit through the yield from;
2. The generator can spit out data one by one by calling the next function, or it can call its own __next__ function;
3. The generator is a special iterator that can traverse the data through the for loop;
# Define the generator function def my_gen(): --my_list = ['I','love','python', 123]--for item in my_list:----yield item# Get the generator gen1 = my_gen( )# Get the data in the generator print(gen1.__next__()) # Iprint(next(gen1)) # love# Define the generator and iterate over its data gen2 = my_gen() for item in gen2:--print(item )
Third. Function definition generator
Define a function externally, define a generator function internally, and the external function returns the name of the generator function
def outer_fn(num=10):--def inner_gen(para=num):----for item in range(para + 1):------yield item ** 2----return inner_geninner_fn = outer_fn(5) # external function execution, return internal function gen = inner_fn() # internal function execution, return generator print(next(gen)) # 0print(next(gen))#1
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.