#-*-Coding:utf-8-*-
# python:2.x
__author__ = ' Administrator '
#迭代器与生成器
#---------------------------------------
#迭代器基于2个方法
"""
Next: Return to the next item in the container
__ITER__: Returns the iterator itself
"""
#通过内建函数和序列来创建
I=iter (' abc ')
Print I.next () #a
Print I.next () #b
Print I.next () #c
#print I.next () exception stopiteration
#当序列遍历完之后, a stopiteration exception occurs, compatible with the loop, and can be obtained by using the Next method class
Class Miter (object):
def __init__ (self,a):
Self.a=a
Def next (self):
If self.a==0:
Raise Stopiteration
Self.a-=1
Return SELF.A
def __iter__ (self):
return self
For El in Miter (4):
Print El
#注意: Iterators are underlying features and concepts that, in general, can be without them in program code
#------------------------------
#生成器
#特点是: simple, efficient, yield-based instructions that can pause a function and return an intermediate result, which must be recoverable
def fib ():
a,b=0,1
While True:
Yield b
A,b=b,a+b
F=FIB ()
Print F.next () #1
Print F.next () #1
Print F.next () #2
Print [F.next () for I in Range] #返回特殊的迭代器, which is the generator object, see: http://www.cnblogs.com/itech/archive/2011/01/19/ 1939119.html
#重点: When you need a function that will return a sequence or execute in a loop, consider the generator
Import Tokenize
#官方文档: https://docs.python.org/2/library/tokenize.html
Reader=open (' a1.py ', ' R '). Next
Tokens=tokenize.generate_tokens (reader)
Print Tokens.next () # (-*-coding:cp936-*-', (1, 0), (1, 23°c), ' #-*-coding:cp936-*-\n ')
#注意: Because there is no advanced programming above that file, you can only use your own files
Print Tokens.next () # (SI, ' \ n ', (1, +), (1, +), ' #-*-coding:cp936-*-\n ')
Print Tokens.next () # (1, ' Def ', (2, 0), (2, 3), ' Def a (A1): \ n ')
Print Tokens.next () # (1, ' A ', (2, 4), (2, 5), ' Def a (A1): \ n ')
"""
The open () function iterates through each line in the file, and Generate_tokens () iterates over it in a single pipe to do some extra work
"""
#例子: The description function is used to define a transformation on the sequence, then be linked to apply, each call will process an element and return its results
def power (values):
For Values2 in values:
Print Values2
Yield Values2
def addr (values):
For value in values:
Print value
If value%2==0:
Yield value+3
Else
Yield value+2
EL=[1,4,7,9,12,19]
Res=addr (Power (EL))
Print Res.next () #1, 1,3
#注意
"""
Keep your code simple, not data {
Having many simple iterative functions that deal with sequence values is better than a complex one that computes one value at a time.
"""
The code interaction function of the #python引入的与生成器最后一个特性是提供了与next () method invocation, yield becomes an expression, and a value can be passed by a new method called send
Def Psy ():
print ' Pleass tell me your problems '
While True:
anwer= (yield)
If Anwer.endswith ('? '):
Print ("Don t ask your self")
Elif ' good ' in Anwer:
print ' Good gon '
Elif ' bad ' in Anwer:
print ' bad '
Pay=psy ()
Pay.next () #pleass tell me your problems
Pay.send (' I Fell bad ') #bad
Pay.send (' Why I shou? ') #don ' t ask your self
#原理
"""
Send works the same way as next, but requires yield to be able to return the legendary value, along with the throw and close functions
Throw allows client code to pass in any type of exception to be recruited
Close works the same way, but will recruit a specific exception <geneartorexit>, in which case the generator function must be geneartorexit again
or stopiteration anomalies.
"""
#典型生成器模板
Def my_geneartorexit ():
Try
Yield ' something '
Except ValueError:
Yield ' dealing with the exception '
Finally
print ' OK clean '
My=my_geneartorexit ()
Print my.next () #ok clean and Something
Print My.throw (valueerror (' mean mean mean ')) #dealing with the exception
My.close () #ok clean
#print My.next () stopiteration
#说明
"""
Finally is not allowed in previous versions, it captures any uncaught close and throw calls and is the recommended way to complete cleanup work.
The geneartorexit exception cannot be caught in the generator because it is used by the compiler to determine whether to exit normally when close is called, and if there is code associated with the exception, then the interpreter throws a system error
and exit
"""