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 |
|
同过上述代码可知,当迭代完所有的元素之后,会抛出StopIteration
的异常:详细信息如下:
in get_iterator_obj_via_iter
ele = next(my_iter) # StopIteration
自定义迭代器:
可以通过创建一个类实现__iter__()
和__next()__
方法来自定义迭代器。
iter() 方法:这个方法返回迭代器对象本身。它使得迭代器对象也是一个可迭代对象,可以在 for 循环中使用。
next() 方法:这个方法返回迭代器的下一个值。当没有更多的值可以返回时,它应该引发 StopIteration 异常。
1 |
|
内置迭代器
Python 也提供了许多内置迭代器.range()、enumerate()、zip()
等
1 |
|
生成器
生成器是Python中一种特殊的迭代器,使用yield
关键字来返回值。生成器允许你在迭代过程中生成值,而不是一次性生成所有值,这使得它们非常适合处理大数据集或无限序列。
生成器的优点
惰性求值:生成器在需要时才生成元素,节省内存。
无限序列:可以表示无限序列,如生成斐波那契数列。
代码简洁:生成器可以用更少的代码生成序列。
创建生成器
- 生成器函数 : 使用yield关键字来返回值
- 生成器表达式: 类似于列表推导式,但使用圆括号而不是方括号 【如】
生成器函数
1 |
|
生成器表达式
1 |
|