zoukankan      html  css  js  c++  java
  • 生成器代替迭代器

    import re
    import reprlib
    
    RE_WORD = re.compile('w+')
    
    '''
    生成器是迭代器
    '''
    
    
    def gen_123():
        print('start')
        yield 'A'
        print('continue')
        yield 'B'
        print('end')
    
    
    for i in gen_123():
        print('-->', i)
    
    '''
    第一个循环:
    start
    --> A
    第二个循环
    continue
    --> B
    第三个循环:
    end
    for循环会捕获stopiteration的异常
    '''
    
    
    class Sentence:
        def __init__(self, text):
            self.text = text
            self.words = RE_WORD.findall(text)
    
        def __repr__(self):
            return 'Setence(%s)' % reprlib.repr(self.text)
    
        def __iter__(self):
            for word in self.words:
                yield word  # 含有yield关键字,就是一个生成器函数
            return
    
    
    '''
    使用生成器代替去实现一个迭代器
    '''
    
    
    # s4 = Sentence('pig and pepper')
    # it = iter(s4)
    # print(it)  # <generator object Sentence.__iter__ at 0x000001C8EA074AF0>
    # print(next(it))
    # print(next(it))
    # print(next(it))
    
    
    # 使用re。finditer返回生成器
    class Sentence2:
        def __init__(self, text):
            self.text = text
    
        def __repr__(self):
            return 'Setence(%s)' % reprlib.repr(self.text)
    
        def __iter__(self):
            for match in RE_WORD.finditer(self.text):
                yield match.group()  # 含有yield关键字,就是一个生成器函数
            return
    
    
    s4 = Sentence2('pig and pepper')
    it = iter(s4)
    # <generator object Sentence.__iter__ at 0x000001C8EA074AF0>
    print(next(it))
    print(next(it))
    print(next(it))

    1

    def gen_123():
        print('start')
        yield 'A'
        print('continue')
        yield 'B'
        print('end')
    
    
    res1 = [x * 3 for x in gen_123()]
    '''
    输出:
    start
    continue
    end
    '''
    
    res2 = (x * 3 for x in gen_123())
    # print(res2)
    # print(next(res2))
    # print(next(res2))
    # print(next(res2))
  • 相关阅读:
    ES 入门记录之 match和term查询的区别
    ElasticSearch 学习记录之Text keyword 两种基本类型区别
    ES 记录之如何创建一个索引映射,以及一些设置
    娱乐至死 读书笔记
    ES 入门之一 安装ElasticSearcha
    王二的经济学故事 读书笔记
    redis特性 存储 API 集群 等
    Linux 卸载 openjdk
    Linux 下面解压.tar.gz 和.gz文件解压的方式
    本地连接 vmware服务器
  • 原文地址:https://www.cnblogs.com/liuer-mihou/p/11903672.html
Copyright © 2011-2022 走看看