码迷,mamicode.com
首页 > 其他好文 > 详细

生成器yield

时间:2017-06-30 14:01:40      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:roo   表达   odi   tar   false   技术   for   ext   send   

生成器函数:函数体内包含yield关键字,该参数执行的结果是生成器函数。生成器本质也是迭代器。

yield

1.与return类似,都可以返回值,但不一样的是yield返回多次值,而return只能返回一次值。

2.为函数封装好__iter__ 和__next__方法,吧函数执行结果做成了迭代器。

3遵循迭代器的取值方式,next(),触发函数的执行,函数暂停与再继续的状态,都是由yield保存

三元表达式

res =  True if 表达式 else False

技术分享
x=2
y=1
res=%dzuida %x if x>y else yzuida
print(res)
View Code

 

列表解析式[i for i in range(100) if 表达式]

生成器表达式(i for i in range(100) if 表达式)

生成器优点:惰性计算,节省内存

生成器用途:模拟管道,惰性计算

面向过程编程:

import os
def deco(func):
    def wrapper(*args,**kwargs):
        g=func(*args,**kwargs)
        next(g)
        return g
    return wrapper
@deco
def search_file(target):
    while True:
        path=yield
        g=os.walk(path)#g是生成器
        for i in g:
            for file_name in i[-1]:
                file_path=r%s\%s %(i[0],file_name)
                target.send(file_path)
@deco
def opener(target):
    while True:
        file_path=yield
        with open(file_path,encoding=utf-8) as f:
            target.send((file_path,f))

@deco
def reader(target):
    while True:
        file_path,f=yield
        for line in f:
            res=target.send((file_path,line))   #grep.send((file_path,line))
            if res:
                break
@deco
def grep(target,word):
    tag = False
    while True:
        file_path, line = yield tag
        tag = False
        if word in line:
            target.send(file_path)
            tag=True
@deco
def printer():
    while True:
        file_path = yield
        print(file_path)
g=search_file(opener(reader(grep(printer(),root))))
g.send(rE:\PYTHON学习\excises\day9)

 

生成器yield

标签:roo   表达   odi   tar   false   技术   for   ext   send   

原文地址:http://www.cnblogs.com/yuyang26/p/7048981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!