流畅的python14 章可迭代的对象、迭代器 和生成器

可迭代的对象、迭代器和生成器

迭代是数据处理的基石。扫描内存中放不下的数据集时,我们要找到一种惰性获取数据项的方式,即按需一次获取一个数据项。这就是迭代器模式(Iterator pattern)。

迭代器用于从集合中取出元素;而生成器用于“凭空”生成元素。通过斐波纳契数列能很好地说明二者之间的区别:斐波纳契数
列中的数有无穷个,在一个集合里放不下。不过要知道,在 Python社区中,大多数时候都把迭代器和生成器视作同一概念。


Sentence类

单词序列

import re
import reprlib
    RE_WORD = re.compile('\w+')
class Sentence:
    def __init__(self, text):
        self.text = text
        self.words = RE_WORD.findall(text) ➊
    def __getitem__(self, index):
        return self.words[index] ➋
    def __len__(self): ➌
        return len(self.words)
    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text) ➍

❶re.findall 函数返回一个字符串列表,里面的元素是正则表达式的
全部非重叠匹配。
❷ self.words 中保存的是 .findall 函数返回的结果,因此直接返回
指定索引位上的单词。
❸ 为了完善序列协议,我们实现了 __len__ 方法;不过,为了让对象
可以迭代,没必要实现这个方法。
❹ reprlib.repr 这个实用函数用于生成大型数据结构的简略字符串表
示形式。

示例 14-2 测试 Sentence 实例能否迭代

>>> s = Sentence('"The time has come," the Walrus said,') #
>>> s
Sentence('"The time ha... Walrus said,') #
>>> for word in s: #
... print(word)
The
time
has
come
the
Walrus
said
>>> list(s) #
['The', 'time', 'has', 'come', 'the', 'Walrus', 'said']

❶ 传入一个字符串,创建一个 Sentence 实例。
❷ 注意,__repr__ 方法的输出中包含 reprlib.repr 方法生成的
...。
❸ Sentence 实例可以迭代,稍后说明原因。
❹ 因为可以迭代,所以 Sentence 对象可以用于构建列表和其他可迭代
的类型。

猜你喜欢

转载自www.cnblogs.com/chenxuming/p/9690444.html