码迷,mamicode.com
首页 > 其他好文 > 详细

? Generators生成器

时间:2014-10-17 21:52:39      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   sp   div   

生成器对象通过它的next方法返回一个值,直到触发StopIteration异常.

你需要做的只是像创建一个函数一样去创建一个生成器,它包含一个yield语句,pyth

on会认yield并将它标记为生成器。当函数执行到执行到yield语句时,它会像return语句一样返回一个值,唯一不同的是,python解释器会返回一个next函数的栈(stack)指引.

创建一个生成器:

 1 def mygenerator():
 2     yield 1
 3     yield 2
 4     yield a
 5 
 6 """    
 7 >>> mygenerator()
 8 <generator object mygenerator at 0x00B18EB8>
 9 >>> g = mygenerator()
10 >>> next(g)
11 1
12 >>> next(g)
13 2
14 >>> next(g)
15 ‘a‘
16 >>> next(g)
17 
18 Traceback (most recent call last):
19   File "<pyshell#5>", line 1, in <module>
20     next(g)
21 StopIteration
22 >>> 
23 ""
 1 >>> x = mygenerator()
 2 >>> x.next()
 3 1
 4 >>> x.next()
 5 2
 6 >>> x.next()
 7 a
 8 >>> x.next
 9 <method-wrapper next of generator object at 0x012EF288>
10 >>> x.next()
11 
12 Traceback (most recent call last):
13   File "<pyshell#12>", line 1, in <module>
14     x.next()
15 StopIteration
16 >>> 

 

 

我们来写一个函数shorten带一个字符列表参数,返回这个列表的缩写值。长度由元音的数量决定。比如loremipsum有四个元音(o,e,i,u)那么下一个返回的缩写将会是前面四个,dolorist-->dolo,这个有两个元音,下一个将返回前面两个字符

 1 #coding=utf-8
 2 def shorten(string_list):
 3     length = len(string_list[0])
 4 
 5     for s in string_list:
 6         length = yield s[:length]
 7 
 8 mystringlist = [loremipsum, dolorist, ametfoobar]
 9 shortstringlist = shorten(mystringlist)
10 result = []
11 
12 try:
13     s = next(shortstringlist)
14     result.append(s)
15 
16     while True:
17         number_of_vovels = len(filter(lambda letter: letter in aeiou,s))
18 
19         #下一个缩写的字符
20         #由上一个的字符串的元音多少决定
21         s = shortstringlist.send(number_of_vovels)
22         result.append(s)
23 
24 except StopIteration:
25     pass
26 
27 
28 """
29 >>> result
30 [‘loremipsum‘, ‘dolo‘, ‘am‘]
31 >>> 
32 """

send()方法允许我们传一个值给生成器

 

? Generators生成器

标签:style   blog   color   io   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/jypwn/p/4032056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!