File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11#!/usr/bin/env python3
22# -*- coding: utf-8 -*-
33
4- import random , math
4+ def each_ascii (s ):
5+ for ch in s :
6+ yield ord (ch )
7+ return '%s chars' % len (s )
58
6- def rnd (count ):
7- while count > 0 :
8- count = count - 1
9- r = random .randint (0 , 100 )
10- print ('-- random number --' )
11- # 返回随机数r:
12- yield r
13- # 代理返回tri(r)的yield,可能有很多次:
14- ok = yield from tri (r )
15- # 相当于:
16- # for x in tri(r):
17- # yield x
18- print ('-- %s --' % ok )
19- return 'done'
20-
21- def tri (r ):
22- yield r * r
23- yield r * r * r
24- # 相当于: raise StopIteration('ok')
25- return 'ok'
9+ def yield_from (g ):
10+ try :
11+ while True :
12+ next (g )
13+ except StopIteration as s :
14+ return s .value
2615
2716def main ():
28- for x in rnd (3 ):
29- print (x )
17+ for x in each_ascii ('abc' ):
18+ print (x ) # => 'a', 'b', 'c'
19+ it = each_ascii ('xyz' )
20+ try :
21+ while True :
22+ print (next (it )) # => 'x', 'y', 'z'
23+ except StopIteration as s :
24+ print (s .value ) # => '3 chars'
25+
26+ # using yield from in main() will change main() from function to generator:
27+ # r = yield from each_ascii('hello')
28+
29+ print (yield_from (each_ascii ('hello' ))) # => '5 chars'
3030
3131main ()
You can’t perform that action at this time.
0 commit comments