• 第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]
    
    写入自己的博客中才能记得长久
  • 相关阅读:
    Python学习【第五篇】:面向对象及相关
    Python之路【第四篇】:模块
    Python之路【第三篇】:python基础(二)
    Python之路【第二篇】:Python基础(一)
    Python之路【第一篇】:Python简介和入门
    Open-source Tutorial
    Algorithms
    Mathematics Base
    Mathematics Base
    Open-source Tutorial
  • 原文地址:https://www.cnblogs.com/heris/p/14737427.html
Copyright © 2020-2023  润新知