Python3使用yield生成器

内容分享4小时前发布
0 1 0
# yield关键字可以定义生成器对象。生成器是一个函数,它生成一个值得序列,以便在迭代器中使用。
# 生成器对应一般用在 for语句、sum() 或其他一些使用序列的操作中
def countdown(n):
    # print(n)
    # print("start countdown: {}".format(n))
    while n > 0:
        yield n
        n -= 1
    return


if __name__ == '__main__':
    c = countdown(5)
    print(type(c))  # <class 'generator'>
    for i in c:
        print(i, end=' ')  # 5 4 3 2 1
    
    print(sum(countdown(10)))  # 55
    print(max(countdown(99)))  # 99
    print(list(countdown(10)))  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    print(tuple(countdown(5)))  # (5, 4, 3, 2, 1)
    print([x * x for x in countdown(5)])  # [25, 16, 9, 4, 1]
    
    y = countdown(2)
    print(y.__next__())
    # 2
    # start countdown: 2
    # 2
    print(y.__next__())  # 1
    # print(c.__next__())  # StopIteration
© 版权声明

相关文章

1 条评论

  • 头像
    读者

    收藏了,感谢分享

    无记录
    回复