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

生成器试题

时间:2019-01-02 23:26:46      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:turn   print   int   color   取值   运行   list   生成器   test   

生成器试题

生成器加载的时候都不运行,只有最后取值的时候才进行运算

 1 def add(n,i):
 2     return n+i
 3 
 4 def test():
 5     for i in range(4):
 6         yield i
 7 
 8 g=test()
 9 
10 for n in [1,2,3]:
11     g=(add(n,i) for i in g)
12 #等价于
13 #####
14 n = 1
15 g=(add(n,i) for i in g)
16 n = 2
17 g=(add(n,i) for i in g)
18 n = 3
19 g=(add(n,i) for i in g)
20 #####
21 n = 1
22 g=(add(n,i) for i in g)
23 n = 2
24 g=(add(n,i) for i in (add(n,i) for i in g))
25 n = 3
26 g=(add(n,i) for i in (add(n,i) for i in (add(n,i) for i in g)))
27 #####
28 n = 1
29 g=(add(n,i) for i in g)
30 n = 2
31 g=(add(n,i) for i in (add(n,i) for i in g))
32 n = 3
33 g=(add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test())))
34 #test()  (0,1,2,3)
35 #####
36 n = 1
37 g=(add(n,i) for i in g)
38 n = 2
39 g=(add(n,i) for i in (add(n,i) for i in g))
40 n = 3
41 g=(add(n,i) for i in (add(n,i) for i in (add(3,i) for i in (0,1,2,3))))
42 #####
43 n = 1
44 g=(add(n,i) for i in g)
45 n = 2
46 g=(add(n,i) for i in (add(n,i) for i in g))
47 n = 3
48 g=(add(n,i) for i in (add(3,i) for i in (3,4,5,6)))
49 #####
50 n = 1
51 g=(add(n,i) for i in g)
52 n = 2
53 g=(add(n,i) for i in (add(n,i) for i in g))
54 n = 3
55 g=(add(3,i) for i in (6,7,8,9))
56 #####
57 
58 print(list(g))

 

生成器试题

标签:turn   print   int   color   取值   运行   list   生成器   test   

原文地址:https://www.cnblogs.com/ccqc/p/10211609.html

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