设为首页 加入收藏

TOP

迭代器,可迭代对象,生成器(二)
2017-10-23 06:06:58 】 浏览:182
Tags:对象 成器
example. The parentheses aren’t always necessary, but it’s easier to
always add them instead of having to remember when they’re needed.


(PEP 342 explains the exact rules, which are that a yield-expression must always be parenthesized except
when it occurs at the top-level expression on the right-hand side of an assignment. This means you can write
val = yield i but have to use parentheses when there’s an operation, as in val = (yield i) + 12.)
Values are sent into a generator by calling its send(value) method. This method resumes the generator’s
code and the yield expression returns the specified value. If the regular __next__() method is called, the
yield returns None.

python 2.4 以及之前,生成器只能产生输出,一旦生成器代码被调用去穿件一个迭代器,当他的执行重新开始时,就没有方式去传递新的信息到函数

你可以传入一些全局变量,或者通过传入一些可变对象,也能分配给变量, 但是这样会引发混乱。

在Python2.5以后,有了很简单的方式去传递值到一个生成器中,yield 变成了表达式,返回一个value, 

val = (yield i)

当你做一些与返回的数据相关的事情的时候,推荐总是加括号包在这个yield表达式,正如上面的例子,括号不是总需要的,但是很简单的加上它,而不是想起需要加括号再去加上这个括号

>>> def counter(maxi):
    i=0
    while i< maxi:
        val=(yield i)
        if val is not None:
            i=val
        else:
            i+=1

            
>>> it=counter(10)
>>> next(it)
0
>>> next(it)
1
>>> it.send(8)
8
>>> next(it)
9

 

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

yield

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

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

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

三元表达式

res =  True if 表达式 else False

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(r'E:\PYTHON学习\excises\day9')
View Code

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇“羊车门”问题 下一篇起名字好难啊!(初识Django)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目