生成器
只要有yield就是生成器函数, yield有返回值,和记录执行到哪里,只能向下执行
函数名+()生成一个生成器 g=foo()
foo().__next__触发启动这个生成器
__next__和yield要一一对应,最后一个yield下边能写不运行
def foo(): print(1) yield 4 print(2) yield 7 g=foo() print(g.__next__()) print(g.__next__())
好处:节省空间
def gen(): for i in range(2000): yield i g=gen() for i in range(10): print(g.__next__())
send()=__next__+传值
def func(): print(44) l=yield 5 print(l) yield 66 g=func() print(g.__next__()) print(g.send('黄瓜味脉动'))
yield from lst
def foo(): lst=[1,2,3,4] yield from lst g=foo() print(g.__next__()) print(g.__next__()) print(g.__next__()) print(g.__next__())
推导式
列表推导式
print([i for i in range(10)]) print([i for i in range (10) if i%2] )
集合推导式
dic={'1':2,'2':3} d={i for i in dic.items()}
字典推导式
lst1=['1','2'] lst2=[2,3] d={lst1[i]:lst2[i] for i in range(2)}
生成器导式
l=(i for i in range(100)) for i in range(10): print(l.__next__())