生成器和推导式

生成器定义:

函数中带yield的就是生成器

 1 def foo():
 2     print(1)
 3     yield 4
 4     print(2)
 5     yield 5
 6     print(3)
 7     yield 6               # 每次执行到yield,没有则报错
 8 g=foo()             # 产生一个生成器
 9 print(g.__next__())
10 print(g.__next__())
11 print(g.__next__())

 

eg:

1 def gen():
2     for i in range(200):
3         yield i
4 g=gen()
5 for i in range(10):
6     print(g.__next__())

生成器本质就是迭代器,拥有惰性机制,每执行__next__()或者next()才会向下执行取值

 

eg:

1 def foo():
2     lst=[1,2,3,5]
3     yield from lst
4 g=foo()
5 print(next(g))
6 print(next(g))
7 print(next(g))
8 print(next(g))
大坑: 生成器函数运行之后. 产生一个生成器. 而不是运行函数
1 def func():
2     print("我叫周润发")
3     yield "林志玲"   # yield表示返回. 不会终止函数的执行
4     print("宝宝干嘛去了??")
5     yield "宝宝回来了"
6     print("宝宝你在干嘛?")
7     # yield "没了"
8 
9 ret = func() # 执行函数, 此时没有运行函数.
此时拿到的是生成器
print("返回值是", ret) # <generator生成器 object func at 0x0000000009E573B8>

send() -> __next__()
send()可以给上一个yield位置传值
 1 def func():
 2     print("韭菜盒子")
 3     a = yield "韭菜鸡蛋"
 4     print("a", a)
 5     b = yield "韭菜西红柿"
 6     print("b", b)
 7     c = yield "火烧"
 8     print("c", c)
 9 
10 gen = func()
11 print(gen.__next__()) # 第一个位置用send没有任何意义,报错,除非 gen.send(None)
12 print(gen.send("篮球")) # 给上一个yield位置传值
13 print(gen.send("足球"))

 

eg:

 1 def eat():
 2      print("我吃什么啊")
 3      a = yield "馒头"
 4      print("a=",a)
 5      b = yield "⼤饼"
 6      print("b=",b)
 7      c = yield "⾲菜盒⼦"
 8      print("c=",c)
 9      yield "GAME OVER"
10 
11 gen = eat() # 获取⽣成器
12 
13 ret1 = gen.__next__()
14 print(ret1)
15 ret2 = gen.send("胡辣汤")
16 print(ret2)
17 ret3 = gen.send("狗粮")
18 print(ret3)
19 ret4 = gen.send("猫粮")
20 print(ret4)

 

列表推导式:

语法:

[结果 语句 条件]
eg:打印1-100偶数的平方
1 lst=[ i**2 for i in range(1,101) if i%2==0]
2 print(lst)

 eg:打印名字中带两个e的名字

1 names=[['tom','meiko','jeffer','wesley'],['alice','jill','anee','haeeae']]
2 lst=[name for el in names for name in el if name.count("e")==2]
3 print(lst)

 

字典推导式:

语法:{结果(key:value)for循环 if条件}
1 lst=[11,22,33] # {0:11,1:22,2:33}
2 dic={i:lst[i] for i in range(len(lst))}
3 print(dic)

 

集合推导式:

语法:{k for 循环 if 条件}

1 dic={'1':2,'2':'6'}
2 d={i for i in dic.items()}
3 print(d)

生成器表达式:

 1 g=(i for i in range(10))    
 2 print(g)                      #<generator object <genexpr> at 0x0000024294CAF4C0>
 3 print(g.__next__()) #0
 4 print(g.__next__())
 5 print(g.__next__())
 6 print(g.__next__())
 7 print(g.__next__())
 8 print(g.__next__())
 9 print(g.__next__())
10 print(g.__next__())
11 print(g.__next__())
12 print(g.__next__())#9

 

posted @ 2019-01-15 18:21  53Dawns  阅读(144)  评论(0编辑  收藏  举报