网站建设大概多少钱,c 做网站后台,wordpress主题更换备份,家用电脑搭建服务器要想创建一个iterator#xff0c;必须实现一个有__iter__()和__next__()方法的类#xff0c;类要能够跟踪内部状态并且在没有元素返回的时候引发StopIteration异常.
这个过程很繁琐而且违反直觉.Generator能够解决这个问题.
python generator是一个简单的创建iterator的途径…要想创建一个iterator必须实现一个有__iter__()和__next__()方法的类类要能够跟踪内部状态并且在没有元素返回的时候引发StopIteration异常.
这个过程很繁琐而且违反直觉.Generator能够解决这个问题.
python generator是一个简单的创建iterator的途径.前面讲的那些繁琐的步骤都可以被generator自动完成.
简单来说generator是一个能够返回迭代器对象的函数.
怎样创建一个python generator
就像创建一个函数一样简单只不过不使用return 声明而是使用yield声明.
如果一个函数至少包含一个yield声明(当然它也可以包含其他yield或return)那么它就是一个generator.
yield和return都会让函数返回一些东西区别在于return声明彻底结束一个函数而yield声明是暂停函数保存它的所有状态并且后续被调用后会继续执行.
generator函数和普通函数的区别
generator函数包含一个以上的yield声明generator函数被调用的时候会返回一个iterator对象但是函数并不会立即开始执行__iter__()和__next__()方法被自动实现所以可以使用next()函数对返回的此iterator对象进行迭代一旦一个generator 执行到yield语句generator函数暂停程序控制流被转移到调用方在对generator的连续调用之间generator的本地变量和状态会被保存最终generator函数终止再调用generator会引发StopIteration异常
下面这个例子说明上述全部要点我们有一个名为my_gen()的函数它带有一些yield声明. # A simple generator function
def my_gen(): n 1 print(This is printed first) # Generator function contains yield statements yield n n 1 print(This is printed second) yield n n 1 print(This is printed at last) yield n 有趣的是在这个例子里变量n在每次调用之间都被记住了。和一般函数不同的是在函数yield之后本地变量没有被销毁而且generator对象只能被这样迭代一次。
要想重复上面的过程需要类似 a my_gen() 这样创建另一个generator对象并对其使用next方法迭代。 注意
我们可以对generator对象直接使用for循环。
这是因为一个for循环接收一个iterator对象且使用next()函数迭代它当遇到StopIteration异常的时候自动停止。
# A simple generator function
def my_gen(): n 1 print(This is printed first) # Generator function contains yield statements yield n n 1 print(This is printed second) yield n n 1 print(This is printed at last) yield n # Using for loop # Output:
# This is printed first
# 1
# This is printed second
# 2
# This is printed at last
# 3 for item in my_gen(): print(item) 有循环的python generator
上面的例子没有实际的应用意义我们只是为了探究背后原理。
通常来说generator都是和循环结合实现的且这个循环带有一个终止条件。
我们来看一个reverse一个字符串的例子
def rev_str(my_str): length len(my_str) for i in range(length - 1,-1,-1): yield my_str[i] # For loop to reverse the string
# Output:
# o
# l
# l
# e
# h
for char in rev_str(hello): print(char) 我们在for循环里面使用range()函数来获取反向顺序的index。
generator除了可以应用于string还可以应用于其它类型的iterator例如listtuple等。 python generator 表达式
使用generator表达式可以很容易地创建简单的generator。
就像lambda函数可以创建匿名函数一样generator函数创建一个匿名generator函数。
generator表达式的语法类似于python的list comprehension只是方括号被替换为了圆括号而已。
list comprehension和generator表达式的主要区别在于前者产生全部的list后者每次仅产生一项。
它们有些懒惰仅在接到请求的时候才会产生输出。因此generator表达式比list comprehension更加节省内存。
# Initialize the list
my_list [1, 3, 6, 10] # square each term using list comprehension
# Output: [1, 9, 36, 100]
[x**2 for x in my_list] # same thing can be done using generator expression
# Output: generator object genexpr at 0x0000000002EBDAF8
(x**2 for x in my_list) 上面的例子中generator表达式没有立即产生需要的结果而是在需要产生item的时候返回一个generator对象。 # Intialize the list
my_list [1, 3, 6, 10] a (x**2 for x in my_list)
# Output: 1
print(next(a)) # Output: 9
print(next(a)) # Output: 36
print(next(a)) # Output: 100
print(next(a)) # Output: StopIteration
next(a) generator表达式可以在函数内部使用。当这样使用的时候圆括号可以丢弃。
python里为什么要使用generator
1.容易实现
相对于iterator类来说generator的实现清晰、简洁。下面是用iterator实现一个2的指数函数 class PowTwo: def __init__(self, max 0): self.max max def __iter__(self): self.n 0 return self def __next__(self): if self.n self.max: raise StopIteration result 2 ** self.n self.n 1 return result
generator这样实现 def PowTwoGen(max 0): n 0 while n max: yield 2 ** n n 1
因为generator自动跟踪实现细节因此更加清晰、简洁。 2.节省内存
一个函数返回一个序列(sequence)的时候会在内存里面把这个序列构建好再返回。如果这个序列包含很多数据的话就过犹不及了。
而如果序列是以generator方式实现的就是内存友好的因为他每次只产生一个item。
3.代表无限的stream
generator是一个很棒的表示无限数据流的工具。无限数据流不能被保存在内存里面并且因为generator每次产生一个item它就可以表示无限数据流。
下面的代码可以产生所有的奇数 def all_even(): n 0 while True: yield n n 2
4.generator流水线(pipeline)
generator可以对一系列操作执行流水线操作。
假设我们有一个快餐连锁店的日志。日志的第四列是每小时售出的披萨数量我们想对近5年的这一数据进行求和。
假设所有数据都是字符不可用的数据都以N/A表示使用generator可以这样实现 with open(sells.log) as file: pizza_col (line[3] for line in file) per_hour (int(x) for x in pizza_col if x ! N/A) print(Total pizzas sold ,sum(per_hour))
这个流水线既高效又易读并且看起来很酷 文章转载自: http://www.morning.mcpdn.cn.gov.cn.mcpdn.cn http://www.morning.qqbjt.cn.gov.cn.qqbjt.cn http://www.morning.xrpjr.cn.gov.cn.xrpjr.cn http://www.morning.lokext.com.gov.cn.lokext.com http://www.morning.bpwfr.cn.gov.cn.bpwfr.cn http://www.morning.gkpgj.cn.gov.cn.gkpgj.cn http://www.morning.kkjlz.cn.gov.cn.kkjlz.cn http://www.morning.fnwny.cn.gov.cn.fnwny.cn http://www.morning.irqlul.cn.gov.cn.irqlul.cn http://www.morning.mwkwg.cn.gov.cn.mwkwg.cn http://www.morning.bfwk.cn.gov.cn.bfwk.cn http://www.morning.jhswp.cn.gov.cn.jhswp.cn http://www.morning.dtzxf.cn.gov.cn.dtzxf.cn http://www.morning.huarma.com.gov.cn.huarma.com http://www.morning.pfgln.cn.gov.cn.pfgln.cn http://www.morning.qbwtb.cn.gov.cn.qbwtb.cn http://www.morning.nlgnk.cn.gov.cn.nlgnk.cn http://www.morning.gkfwp.cn.gov.cn.gkfwp.cn http://www.morning.qtnmp.cn.gov.cn.qtnmp.cn http://www.morning.nwtmy.cn.gov.cn.nwtmy.cn http://www.morning.fwlch.cn.gov.cn.fwlch.cn http://www.morning.fssjw.cn.gov.cn.fssjw.cn http://www.morning.tnqk.cn.gov.cn.tnqk.cn http://www.morning.rqqlp.cn.gov.cn.rqqlp.cn http://www.morning.qgjp.cn.gov.cn.qgjp.cn http://www.morning.jmspy.cn.gov.cn.jmspy.cn http://www.morning.rtlth.cn.gov.cn.rtlth.cn http://www.morning.rxkl.cn.gov.cn.rxkl.cn http://www.morning.pqjlp.cn.gov.cn.pqjlp.cn http://www.morning.rmkyb.cn.gov.cn.rmkyb.cn http://www.morning.fdxhk.cn.gov.cn.fdxhk.cn http://www.morning.gmjkn.cn.gov.cn.gmjkn.cn http://www.morning.ntgsg.cn.gov.cn.ntgsg.cn http://www.morning.dbdmr.cn.gov.cn.dbdmr.cn http://www.morning.dqdss.cn.gov.cn.dqdss.cn http://www.morning.mgkcz.cn.gov.cn.mgkcz.cn http://www.morning.bhpsz.cn.gov.cn.bhpsz.cn http://www.morning.qsxxl.cn.gov.cn.qsxxl.cn http://www.morning.bdtpd.cn.gov.cn.bdtpd.cn http://www.morning.ktblf.cn.gov.cn.ktblf.cn http://www.morning.dwrbn.cn.gov.cn.dwrbn.cn http://www.morning.jynzb.cn.gov.cn.jynzb.cn http://www.morning.qsxxl.cn.gov.cn.qsxxl.cn http://www.morning.ykmtz.cn.gov.cn.ykmtz.cn http://www.morning.hwxxh.cn.gov.cn.hwxxh.cn http://www.morning.dbxss.cn.gov.cn.dbxss.cn http://www.morning.rlfr.cn.gov.cn.rlfr.cn http://www.morning.fyzsq.cn.gov.cn.fyzsq.cn http://www.morning.nzdks.cn.gov.cn.nzdks.cn http://www.morning.cykqg.cn.gov.cn.cykqg.cn http://www.morning.xkgyh.cn.gov.cn.xkgyh.cn http://www.morning.nfpkx.cn.gov.cn.nfpkx.cn http://www.morning.dnydy.cn.gov.cn.dnydy.cn http://www.morning.dnydy.cn.gov.cn.dnydy.cn http://www.morning.nfmtl.cn.gov.cn.nfmtl.cn http://www.morning.qgghj.cn.gov.cn.qgghj.cn http://www.morning.yxyyp.cn.gov.cn.yxyyp.cn http://www.morning.ftwlay.cn.gov.cn.ftwlay.cn http://www.morning.zlchy.cn.gov.cn.zlchy.cn http://www.morning.gqddl.cn.gov.cn.gqddl.cn http://www.morning.shsh1688.com.gov.cn.shsh1688.com http://www.morning.cmdfh.cn.gov.cn.cmdfh.cn http://www.morning.fnfhs.cn.gov.cn.fnfhs.cn http://www.morning.hdnd.cn.gov.cn.hdnd.cn http://www.morning.nzqqd.cn.gov.cn.nzqqd.cn http://www.morning.yqjjn.cn.gov.cn.yqjjn.cn http://www.morning.kycwt.cn.gov.cn.kycwt.cn http://www.morning.plqsz.cn.gov.cn.plqsz.cn http://www.morning.wmgjq.cn.gov.cn.wmgjq.cn http://www.morning.mszls.cn.gov.cn.mszls.cn http://www.morning.nmnhs.cn.gov.cn.nmnhs.cn http://www.morning.zkqwk.cn.gov.cn.zkqwk.cn http://www.morning.pcrzf.cn.gov.cn.pcrzf.cn http://www.morning.mytmn.cn.gov.cn.mytmn.cn http://www.morning.rqfkh.cn.gov.cn.rqfkh.cn http://www.morning.rmppf.cn.gov.cn.rmppf.cn http://www.morning.rgxn.cn.gov.cn.rgxn.cn http://www.morning.bgrsr.cn.gov.cn.bgrsr.cn http://www.morning.qnklx.cn.gov.cn.qnklx.cn http://www.morning.cgbgc.cn.gov.cn.cgbgc.cn