生成器表达式简介

Python 工具箱

Hugo Bowne-Anderson

Data Scientist at DataCamp

生成器表达式

  • 回顾列表推导
[2 * num for num in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  • [ ] 换成 ( )
(2 * num for num in range(10))
<generator object <genexpr> at 0x1046bf888>
Python 工具箱

列表推导 vs. 生成器

  • 列表推导:返回列表
  • 生成器:返回生成器对象
  • 二者均可迭代
Python 工具箱

从生成器打印值(1)

result = (num for num in range(6))

for num in result: print(num)
0
1
2
3
4
5
result = (num for num in range(6))

print(list(result))
[0, 1, 2, 3, 4, 5]
Python 工具箱

从生成器打印值(2)

result = (num for num in range(6))
  • 惰性求值
print(next(result))
0
print(next(result))
1
print(next(result))
2
print(next(result))
3
print(next(result))
4
Python 工具箱

生成器 vs. 列表推导

Python 工具箱

生成器 vs. 列表推导

Python 工具箱

生成器 vs. 列表推导

Python 工具箱

生成器表达式中的条件

even_nums = (num for num in range(10) if num % 2 == 0)

print(list(even_nums))
[0, 2, 4, 6, 8]
Python 工具箱

生成器函数

  • 调用时生成生成器对象
  • 像常规函数用 def 定义
  • yield 产出一系列值,而非返回单个值
  • 用关键字 yield 生成值
Python 工具箱

构建生成器函数

  • sequence.py
def num_sequence(n):
    """Generate values from 0 to n."""
    i = 0
    while i < n:
        yield i
        i += 1
Python 工具箱

使用生成器函数

result = num_sequence(5)

print(type(result))
<class 'generator'>
for item in result:
    print(item)
0
1
2
3
4
Python 工具箱

Passons à la pratique !

Python 工具箱

Preparing Video For Download...