def counter (start_at=0) : count = start_at while True: val = (yield count) if val is not None: count = val else: count +=1 count = counter(5) #建立一个生成器 print(count.__next__()) #向外面返回一个5,然后count 变为6 print(count.__next__()) #返回一个6 print(count.send(9)) #往yield后面传一个值 print(count.__next__()) count.close() #关闭这个生成器 print(count.__next__()) #不能在生成一个新的值了 执行结果: 5 6 9 10 File "I:/untitled/cx/11月/11-6/2生成器函数.py", line 38, in <module> print(count.__next__()) StopIteration
调用next,它就去寻找yield,然后打印后面的值。
第二题
有?个数据结构如下所?,请编写?个函数从该结构数据中返回由指定的字段和对应的值组成的字 典。如果指定字段不存在,则跳过该字段。(10分) data:{"time":"2016-08-05T13:13:05", "some_id":"ID1234", "grp1":{ "fld1":1, "fld2":2}, "xxx2":{ "fld3":0, "fld5":0.4}, "fld6":11, "fld7":7, "fld46":8} fields:由"|"连接的以"fld"开头的字符串,如:fld2|fld3|fld7|fld19 def select(data,fields): TODO:implementation return result
data= {"time":"2016-08-05T13:13:05","some_id":"ID1234","grp1":{ "fld1":1,"fld2":2}, "xxx2":{ "fld3":0,"fld5":0.4},"fld6":11,"fld7":7,"fld46":8} fields = "fld2|fld3|fld7|fld19" 第一种解法 def select(data,fields): result = {} fields_lst = fields.strip().split(‘|‘) for m in data.keys(): if m in fields_lst: result[m] = data[m] elif type(data[m]) == dict: for n in data[m].keys(): if n in fields_lst: result[n] = data[m][n] return result print(select(data,fields)) 第二种解法 def select(data,fields): result = {} result_1={} fields_lst = fields.strip().split(‘|‘) for m in data.keys(): if type(data[m]) == dict: for n in data[m].keys(): result_1[n] = data[m][n] else: result_1[m] = data[m] for k in fields_lst: if k in result_1.keys(): result[k] = result_1[k] return result print(select(data,fields))
3.动态生成平均值
def averager(): total = 0.0 count = 0 average = None while True: term = yield average total += term count += 1 average = total/count g_avg = averager() next(g_avg) print(g_avg.send(10)) print(g_avg.send(30)) print(g_avg.send(5))
4.生成器动态监听文件输入
import time def tail(filename): f = open(filename) f.seek(0, 2) #从文件末尾算起 while True: line = f.readline() # 读取文件中新的文本行 if not line: time.sleep(0.1) continue yield line tail_g = tail(‘tmp‘) for line in tail_g: print(line)
5.金典1
def demo(): for i in range(4): yield i g=demo() g1=(i for i in g) g2=(i for i in g1) print(list(g1)) print(list(g2))
6金典2
def add(n,i): return n+i def test(): for i in range(4): yield i g=test() for n in [1,10]: g=(add(n,i) for i in g) =》(add(10,i) for i in add(10,i) for i in [0,1,2,3])
这是一个生成器,在打印结果之前不会执行。
print(list(g))