003 - Python迭代器与生成器(iterator & generator)

迭代器

An iterable is an object capable of returning its members one at a time. Examples include sequence types (like list, str, and tuple) and some non-sequence types (like dict, file objects, and custom classes with an iter() or getitem() method).

  • Iterable: An object is considered iterable if it implements the iter() method, which returns an iterator.
  • Iterator: An object is considered an iterator if it implements both the iter() and next() methods.

Python supports a concept of iteration over containers.
This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration.

  • iterator.iter() : which return the iterator object itself
  • iterator.next(): which return the next item from the iterator

简单说:
Python 内部的迭代器是通过实现迭代协议(即包含 iter() 和 next() 方法)来工作的。

迭代器的优点
惰性求值:迭代器在需要时才生成元素,节省内存。
无限序列:可以表示无限序列,如生成斐波那契数列。

创建迭代器iter()

​ 可以使用内置的iter()函数将可迭代对象(eg. list, tuple)转成迭代器

1
2
3
4
5
6
7
8
9
10
11
12
13
def get_iterator_obj_via_iter():
my_list = [1,2,3]
# 获取迭代器
my_iter = iter(my_list)
# 使用 next() 函数访问迭代器的元素
ele = next(my_iter) # 1
print(ele)
ele = next(my_iter) # 2
print(ele)
ele = next(my_iter) # 3
print(ele)
ele = next(my_iter) # StopIteration
print(ele)

同过上述代码可知,当迭代完所有的元素之后,会抛出StopIteration 的异常:详细信息如下:

in get_iterator_obj_via_iter
ele = next(my_iter) # StopIteration

自定义迭代器:

​ 可以通过创建一个类实现__iter__()__next()__方法来自定义迭代器。

iter() 方法:这个方法返回迭代器对象本身。它使得迭代器对象也是一个可迭代对象,可以在 for 循环中使用。

next() 方法:这个方法返回迭代器的下一个值。当没有更多的值可以返回时,它应该引发 StopIteration 异常。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MyIterator:
def __init__(self, data: list):
self.data = data
self.index = 0

def __iter__(self):
"""
返回当前迭代器对象
:return:
"""
return self

def __next__(self):
if self.index >= len(self.data):
raise StopIteration
result = self.data[self.index]
self.index += 1
return result

def test_custom_iterator():
my_iter = MyIterator([1,2,3])
for item in my_iter:
print(item)

内置迭代器

Python 也提供了许多内置迭代器.range()、enumerate()、zip()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 使用 range() 迭代器
for i in range(5):
print(i)
"""
0
1
2
3
4
"""

# 使用 enumerate() 迭代器
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)

"""
0 a
1 b
2 c
"""

for a, b in zip([1, 2, 3], ['a', 'b', 'c']):
print(a, b)

"""
1 a
2 b
3 c
"""

生成器

生成器是Python中一种特殊的迭代器,使用yield关键字来返回值。生成器允许你在迭代过程中生成值,而不是一次性生成所有值,这使得它们非常适合处理大数据集或无限序列。

生成器的优点
惰性求值:生成器在需要时才生成元素,节省内存。
无限序列:可以表示无限序列,如生成斐波那契数列。
代码简洁:生成器可以用更少的代码生成序列。

创建生成器

  1. 生成器函数 : 使用yield关键字来返回值
  2. 生成器表达式: 类似于列表推导式,但使用圆括号而不是方括号 【如】

生成器函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def simple_generator():
yield 1
yield 2
yield 3

# 使用生成器
gen = simple_generator()
print(next(gen)) # 输出: 1
print(next(gen)) # 输出: 2
print(next(gen)) # 输出: 3

def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

# 使用生成器
fib_gen = fibonacci_generator()
for _ in range(10):
print(next(fib_gen))
# 输出:
# 0
# 1
# 1
# 2
# 3
# 5
# 8
# 13
# 21
# 34

生成器表达式

1
2
3
4
5
6
7
gen_expr = (x * x for x in range(3))
for value in gen_expr:
print(value)
# 输出:
# 0
# 1
# 4

003 - Python迭代器与生成器(iterator & generator)
https://jackiedai.github.io/2025/03/07/011Python/004Python迭代器与生成器/
Author
lingXiao
Posted on
March 7, 2025
Licensed under