# python学习日记：day14-----生成器进阶

#### 3，列表推导式与生成器表达式的区别

#括号不一样

#返回值不一样  ===》生成器表达式几乎不占内存

g =('鸡蛋%s'%i for i in range(10))

print(g)

for i in g:

print(i)

#### [每一个元素或者是和元素相关的操作  for  元素  in  可迭代数据类型]       #遍历之后挨个处理

`#例:找到嵌套列表中名字含有两个‘e’的所有名字names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'], ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]print([name for lst in names for name in lst if name.count('e') >= 2]) # 注意遍历顺序，这是实现的关键`

#### 4）字典推导式：

`mcase = {'a': 10, 'b': 34}mcase_frequency = {mcase[k]: k for k in mcase}print(mcase_frequency)`

#### 例二：合并大小写对应的value值，将k统一成小写

`mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys()}print(mcase_frequency)`

5)集合推导式：

`squared = {x**2 for x in [1, -1, 2]}print(squared)# Output: set([1, 4])`

5,移动平均值

`def averager(): total = 0.0 count = 0 average = None while True: term = yield average total += term count += 1 average = total/countg_avg = averager()next(g_avg)print(g_avg.send(10))print(g_avg.send(30))print(g_avg.send(5))`

6，预激生成器的装饰器

`def init(func): #在调用被装饰生成器函数的时候首先用next激活生成器 def inner(*args,**kwargs): g = func(*args,**kwargs) next(g) return g return [email protected] averager(): total = 0.0 count = 0 average = None while True: term = yield average total += term count += 1 average = total/countg_avg = averager()# next(g_avg) 在装饰器中执行了next方法print(g_avg.send(10))print(g_avg.send(30))print(g_avg.send(5))`