import time #列表生成式

t=[i*2 for i in range(10)]

print(t)

print(t[8])

生成器:只有在调用的时候生成相应的数据,一种算法。

#只记住当前位置,只有一个_next_方法,取下一个值这个值就是当前值!。只能记住当前的!前面的数据不保存,后面的数据没生成。 c=(i*2 for i in range(100000000)) print(c)

#斐波那契 def fib(max): n,a,b=0,0,1 while n<max: #print(b) yield b #这样做就是一个生成器(函数生成器) a,b=b,a+b n=n+1 return "done"

f=(fib(4)) #生成器调生成一个数据就中断,能进行其他操作 print(f.next()) print("干点其他的事") print(f.next())

抓取异常

g=fib(6) while True: try: x=next(g) print("g:",x) except StopIteration as e: print("vlan:",e.value) break

生成器并行,利用生成器调用中断做其他事再次调用。

def consumer(name): print("%s准备吃包子啦!"%name) while True: baozi=yield print("baozi[%s]来了,被[%s]吃了!"%(baozi,name))

def producer(name1,name2): c=consumer(name1) c2=consumer(name2) c.next() c2.next() print("老子滴开始准备包子啦!") for i in range(10): time.sleep(1) print("做了2个包子!一人一个!") c.send(i) #把值传给yield并调用生成器 c2.send(i)

producer("alex","胡悦")

c=consumer("alex")