标签:面向过程 war 列表 return end 函数 while wal 面向
一.协程函数的应用
写一个装饰器用于让协程函数不需要输入再执行一次next()函数
分析: 在装饰器中生成该协程函数的生成器, 并且执行一次next()函数
def firstNext(func): def wrapper(*args, **kwargs): g = func(*args, **kwargs) next(g) return g return wrapper @firstNext def eater(name): print("{} start to eat".format(name)) food_list = [] while True: food = yield food_list print("{} eat {}".format(name, food)) food_list.append(food) g = eater("egon") print(g.send("包子")) print(g.send("炸酱面"))
实现 grep -rl ‘python‘ c:/test 的功能
一个函数实现
import os def search(dir_name, partten): g = os.walk(dir_name) res = {"",} for i in g: for j in i[-1]: file_path = i[0] + "\\" +j with open(file_path) as f: for line in f: if partten in line: res.add(file_path) for line in res: if line: print(line) search("c:\\test", "python") 利用生成器来处理 import os def firstNext(func): def wrapper(*args, **kwargs): g = func(*args, **kwargs) next(g) return g return wrapper @firstNext def search(target): while True: dir_name = yield g = os.walk(dir_name) for i in g: for j in i[-1]: file_path = i[0] + "\\" +j target.send(file_path) @firstNext def opener(target): while True: file_path = yield with open(file_path) as f: target.send((file_path, f)) @firstNext def cat(target): while True: file_path, f = yield for line in f: target.send((file_path, line)) @firstNext def grep(partten, target): while True: file_path, line = yield if partten in line: target.send(file_path) @firstNext def printer(): while True: file_path = yield print(file_path) g = search(opener(cat(grep("python",printer())))) g.send("c:\\test")
列表生成式的具体形式
列表 = [处理变量形成列表元素 for循环 if判断 for循环2]
等同于
for循环 if判断 for循环 元素=表达式 列表.append(元素)
生成器表达式是 列表生成式的中括号编程圆括号
其中获得的是一个生成器
可以通过 list(获得的生成器) 来快速生成一个列表
标签:面向过程 war 列表 return end 函数 while wal 面向
原文地址:http://www.cnblogs.com/asaka/p/6700425.html