第一種燕鸽,列表生成器:
#列表生成式
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
第二種兄世,函數(shù)生成器:
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
函數(shù)生成器的第二種方式:yield 值
1、調用函數(shù)啊研,得到一個生成器對象御滩。這個函數(shù)沒有執(zhí)行
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發(fā)送參數(shù),發(fā)給這里變量济似。
根據(jù)這個變量的值的不同矫废,可以改變算法的邏輯。
所以碱屁,這種寫法的作用:在運行過程中磷脯,可以改變算法。
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('執(zhí)行A計劃')
i+1
else:
#邏輯代碼
print('執(zhí)行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
執(zhí)行A計劃
0
執(zhí)行B計劃
2