博客
关于我
【从零学习python 】60.探索生成器:迭代的灵活利器
阅读量:585 次
发布时间:2019-03-11

本文共 1367 字,大约阅读时间需要 4 分钟。

生成器

1. 生成器概述

在编程中,生成器是一种非常有用的工具。它允许我们在迭代过程中按需生成数据,而无需一次性生成所有数据。这对于处理大数据量或需要延迟处理的任务尤为重要。生成器在Python中通过生成器表达式(generator expressions)或函数返回生成器对象来实现。

2. 创建生成器的方法

创建生成器有两种主要方式:

L = [x * 2 for x in range(5)]

G = (x * 2 for x in range(5))

这里,L 是一个列表,而 G 是一个生成器。生成器可以通过多种方式使用,如 next() 函数、for 循环或 list() 方法。

next(G) # 输出 0

next(G) # 输出 2 next(G) # 输出 4 next(G) # 输出 6 next(G) # 输出 8

G = (x * 2 for x in range(5))

for x in G: print(x)

输出结果为:02468

3. 使用生成器函数

生成器函数是通过函数定义返回一个生成器对象的。例如,下面的函数 gen() 会返回一个生成器对象:

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

next(f) # 输出 0 f.send('haha') # 输出 haha next(f) # 输出 None f.send('haha') # 输出 haha

f = gen()

f.next() # 输出 0 f.next() # 输出 None f.next() # 输出 None f.next() # 输出 None f.next() # 抛出 StopIteration 异常

4. 进阶案例

以下是一个更复杂的生成器示例,展示了生成器在处理斐波那契数列中的应用:

def fib(n):
current = 0
num1, num2 = 0, 1
while current < n:
yield num1
num1, num2 = num2, num1 + num2
current += 1
return 'done'
f = fib(5)

for num in f: print(num)

输出:0 1 1 2 3

转载地址:http://vtavz.baihongyu.com/

你可能感兴趣的文章
python gRPC测试helloworld
查看>>
python list,str的拼接与转换
查看>>
python matplotlib简单使用
查看>>
python os.system
查看>>
Python os.system执行多条语句,os.system的返回值以及与os.popen的区别
查看>>
Python os和sys模块
查看>>
python os文件/目录
查看>>
Python Package 之 Faker(随机姓名、电话)
查看>>
python pandas TimeStamps到夏令时的本地时间字符串
查看>>
Python Pandas 用顶行替换标题
查看>>
Python Pandas-从DataFrame按类别绘制多个条形图
查看>>
Python PyQt5 将不再显示此消息复选框添加到 QMessageBox
查看>>
Python PyQt5:如何使用 PyQt5 显示错误消息
查看>>
Python pytest 面试题!
查看>>
Python pytz 时区函数返回一个相差 9 分钟的时区
查看>>
python rabbitmq实现简单/持久/广播/组播/topic/rpc消息异步发送可配置Django
查看>>
Python random和json模块
查看>>
Python random模块seed理解
查看>>
python range()函数
查看>>
Python rdflib可传递查询
查看>>