第16条:考虑用生成器来改写直接返回列表的函数

1.验证长字符串空格

def index_words(text):
    result = []
    if text:
        result.append(0)
    for index, letter in enumerate(text):
        if letter ==' ':
            result.append(index+1)
    return result
# 输人一些范例值,以验证该函数能够正常运作:
address = 'Four score and seven years ago. . .'
result = index_words(address)
print(result[:3])
输出:[0, 5, 11]

2.改进为iter生成器函数

def index_words_iter(text):
    if text:
        yield 0
    for index,letter in enumerate(text):
        if letter ==' ':
            yield index + 1
address = 'Four score and seven years ago. . .'
result = list(index_words_iter(address))
print(result[:3],index_words_iter(address))
a = index_words_iter(address)
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
输出:
[0, 5, 11] <generator object index_words_iter at 0x0000000001F38A98>
0
5
11
15
21

3. 读取文件

from itertools import islice
def index_file(handle):
    offset = 0
    for line in handle:
        if line:
            yield offset
        for letter in line:
            offset += 1
            if letter == '':
                yield offset

with open('__init__.py','r') as f:
    it = index_file(f)
    print(it,type(it))
    results = islice(it,0,3)
    print(list(results))
输出: 
<generator object index_file at 0x0000000001DDBF10> <class 'generator'>
[0, 24, 39]
posted @ 2021-05-06 23:44  ty1539  阅读(30)  评论(0编辑  收藏  举报