〖Python〗-- 迭代器与生成器补充
【迭代器与生成器补充】
初步铺垫:
1 2 3 4 5 6 7 8 9 10 11 | python keyword">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 ))
print ( range ( 0 , 100 ))
|
#两种range取值方法:
1 2 3 4 | print ( list ( range ( 100 )))
for i in range ( 100 ):
print (i)
print ( list ( range ( 1 , 100 , 2 )))
|
生成器变形计划:
一级变形:
1 2 3 4 5 6 7 8 9 | def a():
a = 0
while True :
yield a
a = a + 1
print (a().__next__())
print (a().__next__())
|
二级变形:
1 2 3 4 5 6 7 8 9 10 11 12 | def a():
a = 0
while True :
yield a
a = a + 1
l = a()
print (l)
print (l.__next__())
print (l.__next__())
print (l.__next__())
|
三级变形:
1 2 3 4 5 6 7 8 9 10 11 12 13 | def test2():
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
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__())
|
练习二:
母鸡下蛋例子
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)
|
以上是 〖Python〗-- 迭代器与生成器补充 的全部内容,
来源链接:
utcz.com/z/388332.html