python生成器

相当于一种动态加载的形式,比如我们求一个斐波那契数列,这个是一个无限长度的序列,使用列表肯定放不下,所以可以使用生成器来解决。

def fib(max):
    a, b = 0, 1
    for _ in range(max):
        yield b
        a, b = b, a + b
    return 'done'

这个fib函数就变成了一个generator,是一个可迭代对象

print(fib(10))
#输出<generator object fib at 0x7f8f96e5deb8>

可以把它当成一个列表访问

for x in fib(10):
    print(x)
#输出1 1 2 3 5 8 13 21 34

这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
可以使用next函数来访问

def test():
    yield 1
    yield 2
    yield 3
t = test()

print(next(t))#output:1
print(next(t))#output:1
print(next(t))#output:1
print(next(t))#output

利用生成器生成杨辉三角

def triangle():
    _list, new_list = [1], []
    while True:      
        if len(_list)==1:
            yield new_list  
        for times in range(len(_list)):
            if times == 0:
                new_list.append(1)
            else:
                temp = _list[times - 1] + _list[times]
                new_list.append(temp)
        new_list.append(1)
        yield new_list #返回值,然后挂起函数,等待下一次调用
        _list = new_list.copy()#调用后会继续执行下去
        new_list.clear()

n = 0
for result in triangle():
    n += 1
    print(result)
    if n == 10:
        break
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值