zoukankan      html  css  js  c++  java
  • 第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 写Windows Service服务程序
    关于Python 获取windows信息收集
    Pyqt 获取windows系统中已安装软件列表
    Python 打开目录与指定文件
    【转载】Pyqt 编写的俄罗斯方块
    Python win32api提取exe图标icon
    Pyqt QListWidget之缩略图列表
    Pyqt 时时CPU使用情况
    Python 的三目运算
    Chrome Crx 插件下载
  • 原文地址:https://www.cnblogs.com/heris/p/14737427.html
Copyright © 2011-2022 走看看