Python 列表生成式 生成器 迭代器

列表生成式(List Comprehensions)

用于快速生成列表

1
2
>>> [x for x in range(6)]
>>> [0, 1, 2, 3, 4, 5]

生成器(generator)

创建generator的方法有两种
第一种

1
2
3
>>> (x for x in range(6))
>>> <generator object <genexpr> at 0x053DA030>
>>> list((x for x in range(6)))

第二种
带有yield语句的函数是生成器

1
2
3
4
5
6
7
8
#g.py#
def fn():
print("First step")
yield 1
print("Second step")
yield 2
print("Third step")
yield 3

使用生成器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> from g import fn
>>> g = fn()
>>> next(g)
>>> First step
>>> 1
>>> next(g)
>>> Second step
>>> 2
>>> next(g)
>>> Third step
>>> 3
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

迭代器(Iterator)

可在for循环中使用的对象是可迭代对象(iterable)

可在next方法中使用的对象是迭代器(iterator)

所有生成器都是迭代器