9-day9-生成器-列表解析-三元表达式-
迭代器
# 通过迭代器,迭代打印字典: dict_1 = {'as': '1', 'ds': '2', 'cd': '3', 'ss': '4', } d_dict = dict_1.__iter__() while True: try: i = d_dict.__next__() print(i) except StopIteration: break
列表解析
s='hello' s_new = [] for i in s: res = i.upper() s_new.append(res) print(s_new) # 列表解析方法 s = 'hello' res = [i.upper() for i in s] print(res) # 列表解析加判断 l = [1, 31, 73, 56, 55, 22] res = [i for i in l if i > 50]
生成器
# 函数体内包含yield关键字,该函数执行的结果是生成器函数 # def foo(): print('==============> first') yield 1 print('==============> second') yield 2 print('==============> third') yield 4 print('===============> forth') g = foo() for i in g: print(i) l = foo().__iter__() print(l.__next__()) print(l.__next__()) print(l.__next__()) # yield功能: # 1 与return类似,都可以返回值,但不一样的地方在于yield返回多次,尔return返回一次 # 2 为函数封装好了 __iter__ 和__next__ 方法,把函数执行结果做成了迭代器 # 3. 遵循迭代器的取值方法 obj.__next__() 除法函数的执行,函数暂停与再继续的状态是由yield保存 def countdown(n): print('start countdown') while n > 0: yield n n -= 1 print('stop countdown') g = countdown(5) for i in g: print(i) # 实现 tail -f 功能 import time def tail(): with open('a.txt', 'r', encoding='utf-8') as f: f.seek(0, 2) while True: line = f.readline() if line: print(line,end='') else: time.sleep(0.3) tail() # 实现tail | grep 功能 import time def tail(filename): with open(filename, 'r', encoding='utf-8') as f: f.seek(0, 2) while True: line = f.readline() if line: yield line else: time.sleep(0.3) def grep(lines,pattern): print('lines', lines) for line in lines: if pattern in line: print(line) g = tail('a.txt') grep(g,'errpr') # 实现tail | grep 功能 import time def tail(filename): with open(filename, 'r', encoding='utf-8') as f: f.seek(0, 2) while True: line = f.readline() if line: yield line else: time.sleep(0.3) def grep(lines, pattern): print('lines', lines) for line in lines: if pattern in line: print(line) g = tail('a.txt') grep(g, 'error') # 设计实现 tail + grep + grep import time def tail(filename): with open(filename, 'r', encoding='utf-8') as f: f.seek(0, 2) while True: line = f.readline() if line: yield line else: time.sleep(0.4) t = tail('a.txt') def grep(lines, pattern): for line in lines: if pattern in line: yield line g = grep(t, 'alex') g_2 = grep(g, '3714') for xx in g_2: print(xx)