1 #!/usr/bin/python2 defPower (values):3 forValueinchvalues:4 Print "powing%s"%value5 yieldvalue6 defAdd (values):7 forValueinchvalues:8 ifValue% 2 = =0:9 yieldValue + 3Ten Else: One yieldValue + 2 Aelements = [1, 4, 7, 9, 12, 19] - Add (Power (elements)) - forIinchAdd (Power (elements)): the Print(i)
First look at the result of the above code:
Powing 1
3
Powing 4
7
Powing 7
9
Powing 9
11
Powing 12
15
powing 19
21st
Power is no longer a function, it is a generator, note that power does not execute print during the call, but when it is traversed with for, it executes print, so you first need to know that this is the difference between the generator and the function!! Many tutorials even the most basic functions and the difference between the generator is not mentioned!! The next step is to say the difference between a generator and an iterator:
1. In terms of grammar:
The generator is created with the yield statement in the function. The creation of iterators is first of all function-independent and can be created with ITER ([up]).
2. In terms of use:
Because the generator is created using a function, all the procedures inside the generator are executed, but note that the process inside the generator is executed only when it is called by the next () or for loop, as the above example simply calls the Add object. The process inside the add is not executed!
Iterators can also be called for and next but because there are no other procedures, only values are returned when called, and no other action
The difference between iterators and generators in Python