〖Python〗-- 迭代器与生成器补充
【迭代器与生成器补充】
初步铺垫:
1
2
3
4
5
6
7
8
9
10
11
|
for i in [ 1 , 2 , 3 , 4 ]: pass l = [ 1 , 2 , 3 , 4 ] l2 = iter (l) print (l2.__next__()) print (l2.__next__) print ( range ( 100 )) #range(100) 就是一个生成器,为了节省内存,值不会直接输出 print ( range ( 0 , 100 )) |
#两种range取值方法:
1
2
3
4
|
print ( list ( range ( 100 ))) #通过列表 for i in range ( 100 ): #通过for循环 print (i) print ( list ( range ( 1 , 100 , 2 ))) #步长 |
生成器变形计划:
一级变形:
1
2
3
4
5
6
7
8
9
|
def a(): a = 0 while True : # return a yield a a = a + 1 print (a().__next__()) print (a().__next__()) #全是0,每次重新执行那个函数,这个函数就会重新执行 |
二级变形:
1
2
3
4
5
6
7
8
9
10
11
12
|
def a(): a = 0 while True : # return a yield a a = a + 1 l = a() print (l) print (l.__next__()) #next可以递归的取值,是因为l始终指得是一个函数 print (l.__next__()) print (l.__next__()) |
三级变形:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
def test2(): # for i in range(1,6): # yield i #冻结 yield 1 yield 2 yield 3 yield 4 yield 5 l = test2() print (l.__next__()) print (l.__next__()) print (l.__next__()) |
四级变形:(模拟range功能)
1
2
3
4
5
6
7
8
|
def range2(): start = 0 while start< 10 : yield start * 4 start + = 1 for i in range2(): print (i) |
五级变形:
1
2
3
4
5
6
7
8
|
def range2(): start = 0 l = [] while start< 100 : l.append(start * 4 ) start + = 1 return l print (range2()) |
六级变形:
1
2
3
4
5
6
7
8
9
|
def range3(): start = 0 while True : yield start * 4 start + = 1 # print(range3()) for i in range3(): print (i) |
练习变形计划
练习一:
"1+1+2+3+5..." #斐波那契数列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#初步: def test(): a,b = 1 , 1 while a< 10 : c = a + b yield c a = b b = c print (test()) l = test() print (l.__next__()) print (l.__next__()) for i in l: print (i) #终极: def test4(): a = 1 yield a b = 1 yield b while True : c = a + b yield c a = b b = c l = test4() print (l.__next__()) print (l.__next__()) print (l.__next__()) print (l.__next__()) print (l.__next__()) # for i in l: # print(i) |
练习二:
母鸡下蛋例子
1
2
3
4
5
6
7
8
9
10
11
12
13
|
def test3(): i = 0 while i < 10 : yield '母鸡下了个蛋,这是第%s个蛋' % (i + 1 ) i + = 1 l = test3() print (l.__next__()) print (l.__next__()) print (l.__next__()) for i in l: print (i)
|
年轻时不多经历一点,老了拿什么下酒.