Python iterator and generator use instance, python generator instance
I. Iterators
The iterator is only a container object and implements the iterator protocol. It has two basic methods:
1) next Method
Returns the next element of the container.
2) _ iter _ Method
Return iterator itself
The iterator can be created using the built-in iter method. See the example below:
Copy codeThe Code is as follows:
>>> I = iter ('abc ')
>>> I. next ()
'A'
>>> I. next ()
'B'
>>> I. next ()
'C'
>>> I. next ()
Traceback (most recent call last ):
File "<string>", line 1, in <string>
StopIteration:
Class MyIterator (object ):
Def _ init _ (self, step ):
Self. step = step
Def next (self ):
"Returns the next element ."""
If self. step = 0:
Raise StopIteration
Self. step-= 1
Return self. step
Def _ iter _ (self ):
"Returns the iterator itself ."""
Return self
For el in MyIterator (4 ):
Print el
--------------------
Result:
Copy codeThe Code is as follows:
3
2
1
0
Ii. Generators
Since Python2.2, the generator provides a simple way to return functions of list elements to complete simple and effective code.
It allows you to stop a function and return results immediately based on the yield command.
This function saves the execution context. If necessary, you can continue execution immediately.
For example, the Fibonacci function:
Copy codeThe Code is as follows:
Def maid ():
A, B = 0, 1
While True:
Yield B
A, B = B, a + B
Fib = maid ()
Print fib. next ()
Print fib. next ()
Print fib. next ()
Print [fib. next () for I in range (10)]
--------------------
Result:
Copy codeThe Code is as follows:
1
1
2
[3, 5, 8, 13, 21, 34,55, 89,144,233]
PEP Python Enhancement Proposal Python Enhancement suggestions
Tokenize Module
Copy codeThe Code is as follows:
>>> Import tokenize
>>> Reader = open ('C:/temp/py1.py'). next
>>> Tokens = tokenize. generate_tokens (reader)
>>> Tokens. next ()
(1, 'class', (1, 0), (1, 5), 'class MyIterator (object):/N ')
>>> Tokens. next ()
(1, 'myiterator', (1, 6), (1, 16), 'class MyIterator (object):/N ')
>>> Tokens. next ()
(51, '(', (1, 16), (1, 17), 'class MyIterator (object):/N ')
Example:
Copy codeThe Code is as follows:
Def power (values ):
For value in values:
Print 'powering % s' % value
Yield value
Def adder (values ):
For value in values:
Print 'adding to % s' % value
If value % 2 = 0:
Yield value + 3
Else:
Yield value + 2
Elements = [,]
Res = adder (power (elements ))
Print res. next ()
Print res. next ()
--------------------
Result:
Copy codeThe Code is as follows:
Powering 1
Adding to 1
3
Powering 4
Adding to 4
7
Keep code simple, not data.
Note: You would rather have a large number of simple iteratable functions than a complex function that calculates only one value at a time.
Example:
Copy codeThe Code is as follows:
Def psychologist ():
Print 'Please tell me your problems'
While True:
Answer = (yield)
If answer is not None:
If answer. endswith ('? '):
Print ("Don't ask yourself too much questions ")
Elif 'good' in answer:
Print "A that's good, go on"
Elif 'bad' in answer:
Print "Don't be so negative"
Free = psychologist ()
Print free. next ()
Print free. send ('I feel bad ')
Print free. send ("Why I shouldn't? ")
Print free. send ("OK then I shocould find what is good for me ")
--------------------
Result:
Copy codeThe Code is as follows:
Please tell me your problems
None
Don't be so negative
None
Don't ask yourself too much questions
None
A that's good, go on
None