Python关于迭代器和生成器
本文最后更新于:1 年前
1 - 使用迭代器实现Sentence类
1.1 具体的实现代码
import re
import reprlib
RE_WORD = re.compile('\w+')
class Sentence:
"""定义了一个Sentence类,通过索引从文本中提取单词"""
def __init__(self, text):
self.text = text
# re.findall函数返回一个字符串列表,里面的元素是正则表达式的
全部非重叠匹配
self.words = RE_WORD.findall(text)
def __getitem__(self, index):
return self.words[index]
def __len__(self):
return len(self.words)
def __repr__(self):
# reprlib.repr这个实用函数用于生成大型数据结构的简略字符串表示形式
return 'Sentence(%s)' % reprlib.repr(self.text)
1.2 测试用例
if __name__ == '__main__':
s = Sentence('"The times has come, " Walrus said,')
print(s)
for word in s:
print(word)
print(list(s))
1.3 输出示例
Sentence('"The times h... Walrus said,')
The
times
has
come
Walrus
said
['The', 'times', 'has', 'come', 'Walrus', 'said']
2 - 使用生成器函数实现Sentence类
2.1 具体的实现代码
import re
import reprlib
RE_WORD = re.compile('\w+')
class Sentence:
"""定义了一个Sentence类,通过索引从文本中提取单词"""
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
def __repr__(self):
return 'Sentence(%s)' % reprlib.repr(self.text)
def __iter__(self):
for word in self.words:
yield word
return
# 惰性实现
import re
import reprlib
RE_WORD = re.compile('\w+')
class Sentence:
"""定义了一个Sentence类,通过索引从文本中提取单词"""
def __init__(self, text):
self.text = text
def __repr__(self):
return 'Sentence(%s)' % reprlib.repr(self.text)
def __iter__(self):
for match in RE_WORD.finditer(self.text):
yield match.group()
2.2 测试用例和输出示例和上面一样
3 - 使用生成器表达式实现Sentence类
3.1 具体的实现代码
class Sentence:
def __init__(self, text):
self.text = text
def __repr__(self):
return 'Sentence(%s)' % reprlib.repr(self.text)
def __iter__(self):
return (match.group() for match in RE_WORD.finditer(self.text))
3.2 测试用例和输出示例和上面一样
生成器表达式是语法糖:完全可以替换成生成器函数,不过有时使用生成器表达式更便利
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!