python 生成器 迭代器 用法最全总结(7种典型的用法)

1.利用__getitem__()让编译器自动遍历生成

import re #后面省略书写

RE_WORD = re.compile('\w+')#后面省略书写

class Sentence1:

    def __init__(self,text):
        self.text = text
        self.words = RE_WORD.findall(text)#返回匹配列表
    def __getitem__(self,index):
        return self.words[index]

s1 = Sentence1('"the time make god and gost" mir ding said') #可遍历输出

2.利用__iter__()调用 自定义类型 的生成器函数

class Sentence2:
    def __init__(self,text):
        self.text = text
        self.words = RE_WORD.findall(text)
    def __iter__(self):
        return iter(self.words)#利用列表的__iter__返回生成器

s2 = Sentence2('"the time make god and gost" mir ding said')#可遍历输出

3.典型的方法(啰嗦但是却标准的无可反驳,不是懒人的做法)

class Sentence3:

    def __init__(self,text):
        self.text = text
        self.words = RE_WORD.findall(text)
    def __iter__(self):
        return Sentence3Iterator(self.words)#利用对应的生成器类,实例化生成器对象

class Sentence3Iterator:
    
    def __init__(self,words_list):
        self.words_list = words_list
        self.pos = 0
    def __next__(self):
        try:
            word = self.words_list[self.pos]
        except IndexError:
            raise StopIteration()
        self.pos +=1
        return word
    def __iter__(self):
        return self

s3 = Sentence3('"the time make god and gost" mir ding said')#可遍历输出

4.利用生成器函数yield 简单高效

class Sentence4:

    def __init__(self,text):
        self.text = text  #拷贝的引用,并不占用太多内存
        self.words = RE_WORD.findall(text)#建立所有单词的列表,占用大量内存,接下来优化
    def __iter__(self):
        for word in self.words:
            yield word
        return  #可有可无
    
s4 = Sentence4('"the time make god and gost" mir ding said')#可遍历输出

5.惰性实现,节省内存

class Sentence5:

    def __init__(self,text):
        self.text = text  
        
    def __iter__(self):
        for word in RE_WORD.finditer(self.text):#finditer返回一个迭代器
            yield word.group()
        return  
    
s5 = Sentence5('"the time make god and gost" mir ding said')#可遍历输出

6.利用生成器表达式进一步简化,生成器表达式返回一个新的生成器

class Sentence6:

    def __init__(self,text):
        self.text = text  
        
    def __iter__(self):
        return  ( word.group() for word in RE_WORD.finditer(self.text)) #语法糖跟生成器函数一样
    
s6 = Sentence6('"the time make god and gost" mir ding said')#可遍历输出

7.yield from (整个迭代器"搬过来"用)

class Sentence7:

    def __init__(self,text,text_added):
        self.text = text  
        self.text_added = text_added
    def __iter__(self):
            yield from ( word.group() for word in RE_WORD.finditer(self.text))
            yield from ( word.group() for word in RE_WORD.finditer(self.text_added))
    
s7 = Sentence7('"the time make god and gost" mir ding said',"conclusion: i love time")#可遍历输出
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值