第一种,列表生成器:
#列表生成式
ls = [x for x in range(10)]
print(ls)
运行结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#生成器
ge = (x**2 for x in range(10))
print(ge)
print(type(ge))
num1 = next(ge)
print(num1)
num1 = next(ge)
print(num1)
num1 = next(ge)
print(num1)
num1 = next(ge)
print(num1)
for i in ge:
print(i)
i = 0
while i<19:
next(ge)
i+=1
print(next(ge))
#print(ge.__next__())
运行结果:
<generator object <genexpr> at 0x000000000081A200>
<class 'generator'>
0
1
4
9
16
25
36
49
64
81
Traceback (most recent call last):
File "D:\个人文件\课堂代码练习\11.py", line 22, in <module>
next(ge)
StopIteration
第二种,函数生成器:
def fib(times):
n = 0
a,b = 0,1
while n<times:
print(b)
a,b = b,a+b
n+=1
return 'over'
ret = fib(5)
print(ret)
运行结果:
1
1
2
3
5
over
函数生成器的第二种方式:yield 值
1、调用函数,得到一个生成器对象。这个函数没有执行
2、next调用1得到的对象,如果遇到了yield,代码会阻塞,next的返回值就yield后的值
def fib(times):
print('0....')
n = 0
a,b = 0,1
while n<times:
print('1....')
yield b
print('2....')
a,b = b,a+b
n+=1
print('3....')
#return 'over'
ge = fib(5)
print(ge)
print('*'*50)
print(next(ge))
print(next(ge))
print(next(ge))
print(next(ge))
print(next(ge))
print(next(ge))
def f(num):
print('1...')
yield num
print('2...')
ge = f(100)
print(type(ge))
ret1 = next(ge)
print(ret1)
ret1 = next(ge)
print(ret1)
运行结果:
<generator object fib at 0x000000000071A200>
**************************************************
0....
1....
1
2....
1....
1
2....
1....
2
2....
1....
3
2....
1....
5
<class 'generator'>
1...
100
2...
Traceback (most recent call last):
File "D:\个人文件\课堂代码练习\11.py", line 35, in <module>
ret1 = next(ge)
StopIteration
第一种和第二种,一旦生成器确定,算法不能改变。
这里的例子,定义了变量(temp),可以使用send发送参数,发给这里变量。
根据这个变量的值的不同,可以改变算法的逻辑。
所以,这种写法的作用:在运行过程中,可以改变算法。
def gen():
i = 0
while i<5:
temp = yield i
print('temp=%s'%temp)
i+=1
myGenerator = gen()
print(next(myGenerator))
print(next(myGenerator))
print(next(myGenerator))
next(myGenerator)
myGenerator.send('老王')
运行结果:
0
temp=None
1
temp=None
2
temp=None
temp=老王
def gen():
i = 0
while i<1000:
temp = yield i
if temp==True:
#逻辑代码
print('执行A计划')
i+1
else:
#逻辑代码
print('执行B计划')
i+=2
myGenerator = gen()
ret = next(myGenerator)
print(ret)
#1、为当前停止的代码的左侧变量赋值 2、生成器往下走一个行,返回yield值
ret = myGenerator.send(True)
print(ret)
ret = myGenerator.send(False)
print(ret)
运行结果:
0
执行A计划
0
执行B计划
2