def tail(filename): f = open(filename,encoding='utf-8') while True: line = f.readline() if line.strip(): yield line.strip() g = tail('file') for i in g: if 'python' in i: print('***',i)
#预激生成器的装饰器 def init(func): #装饰器 def inner(*args,**kwargs): g = func(*args,**kwargs) #g = average() g.__next__() return g return inner @init def average(): sum = 0 count = 0 avg = 0 while True: num = yield avg sum += num # 10 count += 1 # 1 avg = sum/count avg_g = average() #===> inner ret = avg_g.send(10) #传入参数 print(ret) ret = avg_g.send(20) print(ret)
# send # send的作用范围和next一模一样 # 第一次不能用send # 函数中的最后一个yield不能接受新的值
#python 3 def generator(): a = 'abcde' b = '12345' yield from a yield from b g = generator() for i in g: print(i)
egg_list=['鸡蛋%s'%i for i in range(10)] #列表推导式 print(egg_list)
#生成器表达式 g = (i for i in range(10)) print(g) for i in g: print(i)
#30以内所有能被3整除的数 ret = [i for i in range(30) if i%3 == 0] #完整的列表推导式
# 例三:找到嵌套列表中名字含有两个‘e’的所有名字 names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'], ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']] ret = [name for lst in names for name in lst if name.count('e') ==2] print(ret)
# 例一:将一个字典的key和value对调 mcase = {'a': 10, 'b': 34} #{10:'a' , 34:'b'} mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency)
#集合推导式,自带结果去重功能 squared = {x**2 for x in [1, -1, 2]} print(squared)