python生成器

2017-06-28  本文已影响158人  Oo晨晨oO

python生成器是用来代替"不一定能够使用全部元素的数组",等到使用某一元素时,才生成该元素,用来节省空间.
python生成器写法有两种

第一种:(数组生成式的中括号变成小括号)

# 生成器
arr = (x for x in range(1,6))

# 生成器下一个元素用next()来取得
print("--next1--")
print(next(arr))

print("--next2--")
print(next(arr))

print("--next3--")
print(next(arr))

输出结果:

--next1--
1
--next2--
2
--next3--
3



第二种方式: 使用关键字 yield 关键字

# 斐波那契数列生成器
def creatNum():
    print("---开始执行生成器方法---")
    a,b = 0,1
    for i in range(0,5):
        print("--step1--")
        yield b
        print("--step2--")
        a,b = b,a+b
        print("--step3--")
    print("--..stop..--")

print("直接调用方法...")
print(creatNum())

#这里用一个标识符来指向生成器(不要把creatNum()当做函数)
func = creatNum()

#一次生成
print("使用next调用")
x = next(func)
print(x)

#又一次生成
print("使用next调用")
x = next(func)
print(x)

print("使用next调用")
x = next(func)
print(x)

输出结果:

直接调用方法...
<generator object creatNum at 0x102115f10>
使用next调用
---开始执行生成器方法---
--step1--
1
使用next调用
--step2--
--step3--
--step1--
1
使用next调用
--step2--
--step3--
--step1--
2

生成器还可以用 生成器.next 来调用,等价于 next(生成器)
如果使用next来调用,调用到生成器执行完毕,就会崩掉. 我们基本不会使用next来执行生成器
一般来说会用for循环来执行生成器:

# 斐波那契数列生成器
def creatNum():
    print("---开始执行生成器方法---")
    a,b = 0,1
    for i in range(0,5):
        print("--step1--")
        yield b
        print("--step2--")
        a,b = b,a+b
        print("--step3--")
    print("--..stop..--")

print("直接调用方法...")
print(creatNum())

#这里用一个标识符来指向生成器(不要把creatNum()当做函数)
func = creatNum()

#使用for循环来执行生成器
for i in func:
    print(i)

输出结果: (执行完毕不会崩溃)

直接调用方法...
<generator object creatNum at 0x101c30f10>
---开始执行生成器方法---
--step1--
1
--step2--
--step3--
--step1--
1
--step2--
--step3--
--step1--
2
--step2--
--step3--
--step1--
3
--step2--
--step3--
--step1--
5
--step2--
--step3--
--..stop..--

在执行生成器时,可以使用 生成器.send(param) 方法
send方法不光是执行一步next操作,还会把send里面的参数传到生成器中充当yield表达式的返回值
**(注意:第一次执行,send里面的参数应该为None,或者使用next方法)

def test():
    i = 0
    while i < 5:
        temp = yield i
        print(temp)
        i += 1

t = test()

#先使用next执行,看能出来什么结果
t.__next__()
t.__next__()
print(t.__next__())

#使用send执行
t.send("1231231231223123")
print(t.send("hahahahhahaha"))

输出结果: (可见next输出temp为none , 而send 则把值传递进了生成器)

None
None
2
1231231231223123
hahahahhahaha
4
上一篇下一篇

猜你喜欢

热点阅读