Python iterator and Generator

Source: Internet
Author: User

Python iterator and Generator

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:
>>> 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:
3
2
1
0

Ii. Generators
Since python2.2, the generator provides a simple way to help return functions of list elements to complete simple and effective functions.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:
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:
1
1
2
[3, 5, 8, 13, 21, 34,55, 89,144,233]

Pep Python enhancement proposal Python enhancement suggestions

Tokenize Module
>>> 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:
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:
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:
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:
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

Related Article

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.