栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

生成器 代替迭代器 yield

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

生成器 代替迭代器 yield

 生成器

def gen_123():
    yield 1
    yield 2
    yield 3

def x():
    print(gen_123)
    [print(i) for i in gen_123()]
    g = gen_123()
    next(g)
    next(g)
    next(g)
def gen_AB():
    print('start')
    yield 'A'
    print('continue')
    yield 'B'
    print('end')
def y():
    [print('-->', c) for c in gen_AB()]

惰性实现
RE_WORD = re.compile('w+')
class Sentence:
    def __init__(self, text):
        self.text = text
    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)
    def __iter__(self):
        for match in RE_WORD.finditer(self.text):
            yield match.group()

def y():
    s = Sentence('pig and dog')
    # it = iter(s)
    # print(next(it))
    # print(next(it))
    for i in s:
        print(i)
y()
生成器表达式
import re, reprlib
from collections import abc

RE_WORD = re.compile('w+')
class Sentence:
    def __init__(self, text):
        self.text = text
    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)
    def __iter__(self):
       return (match.group() for match in RE_WORD.finditer(self.text))

def gen_AB():
    print('start')
    yield 'A'
    print('continue')
    yield 'B'
    print('end')

def y():
    res1 = [x*3 for x in gen_AB()]
    [print('-->', i) for i in res1]
    print('----------------')
    res2 = (x*3 for x in gen_AB())  #返回的生成器并不在这使用
    [print('-->', i) for i in res2]
y()

sentence_gen3.py--->
start
continue
end
--> AAA
--> BBB
----------------
start
--> AAA
continue
--> BBB
end

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/268525.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号