1. 程式人生 > >10.3生成器yieldsend

10.3生成器yieldsend

Python 生成器 yield send

生成器yield\send

生成器的好處:緩解內存壓力

# -*-coding:utf-8 -*-
__date__ = ‘2018/3/9 ‘
__author__ = ‘xiaojiaxin‘
__file_name__ = ‘生成器‘

# a1=[x for x in range(5000000000)]
#將range(5000000000)全部扔進內存,速度非常慢,甚至會死機
a=(x for x in range(5))
print(a)
# <generator object <genexpr> at 0x0000003FB1622990>
#a變成生成器的對象,值不在a裏面,把range(10)比喻成10道菜,a是廚師,a一次只做一道菜到內存
#調用數據
print(next(a))   # 內置方法,python3通用方法
# 0
print(next(a))
# 1
print(next(a))
# 2
print(a.__next__())   #內部方法
# 3
print(next(a))
# 4
#print(next(a))
# Traceback (most recent call last):
#   File "C:/Users/xiaojiaxin/PycharmProjects/fullstack1/week2/day9/生成器.py", line 25, in <module>
#     print(next(a))
# StopIteration
a=(x*x for x in range(5))
#生成器就是一個可叠代對象
for i in a:  #for循環對x內部進行了next()調用
    print(i)
# 0
# 1
# 4
# 9
# 16
#生成器一共有兩種創建方式:1:() 2.yield關鍵字

def foo1():
    print("foo1")
    return 1
print(foo1)
# <function foo1 at 0x000000CAEBECD158>
print(foo1())   #執行函數
# foo1
# 1

def foo():
    print("ok11")
    yield   1

    print("ok22")
    yield   2

print(foo)
# <function foo at 0x000000CBE62E2E18>
g=foo()
print(g)  #不執行函數
# <generator object foo at 0x000000CBE8002990>

#執行生成器
next(g)
# ok11
next(g)
# ok22

#next(g)#報錯

for i in foo():
    print(i)
# ok11
# 1
# ok22
# 2
#for i in  可叠代對象:
#檢查一個對象是否為可叠代對象,有__iter__()內部方法
# l=[1,2,3]
# l.__iter__()
# t=(1,2,3)
# t.__iter__()
# d={1:"ok1",2:"ok2"}
# d.__iter__()
#列表,字典,元組之所有可以用for循環,是因為他們都是可叠代對象
#斐波那契數列
#0 1 1 2 3 5 8 13 21
#用遞歸函數方法
def feibo(n):
    if n==1:
        return 0
    elif n==2:
        return  1
    else:
        return feibo(n-1)+feibo(n-2)
print(feibo(9))
# 21
#0 1 1 2 3 5 8 13 21
def fibo(max):
    before,after=0,1
    n=0
    while n<max :
        print(after)
        before,after=after,before+after  #先執行右邊
        n+=1

fibo(5)
#用生成器做斐波那契數列
def fibon(max):
    before,after=0,1
    n=0
    while n<max :
        before,after=after,before+after  #先執行右邊
        n+=1
        yield before
print(fibon(1))  #生成器對象地址
for i in fibon(5):
    print(i)

順便說一下:學生成器yield,是為了日後學習協程,非常關鍵的知識點

def bar():
    print("ok1")
    ret=yield  1
    print(ret)

    print("ok2")
    print(ret)
    ret2=yield 2
    print(ret2)

    print("ok3")
    print(ret)
    print(ret2)
    yield 3

b=bar()
print(b)
print(next(b))

#第一次send如果沒有next(),只能傳send(None)
b.send("edh")
b.send("gghg")

# send()將yield值返回

大家對內容有任何問題,歡迎留言,定在第一時間解答,謝謝大家!

10.3生成器yield\send