#Author by Andy#_*_ coding:utf-8 _*_import timefrom collections import Iterable#列表生成式 def func(): list=[] for i in range(10000000): list.append(i) print(list)#print(list)#[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]generator=(i for i in range(10)) #print(type(generator))def func1(): for i in generator: print(i)def timmer(): time_start=time.time() func1() time_stop=time.time() print(time_stop-time_start)#定义斐波那契数列def fib(max): n,a,b=0,0,1 while n < max: print(b) a,b=b,a+b n=n+1fib(10)# 注意,赋值语句:# a, b = b, a + b# 相当于:# t = (b, a + b) # t是一个tuple# a = t[0]# b = t[1]def fib(max): n,a,b=0,0,1 while n < max: yield b a,b=b,a+b n=n+1 return ‘done‘f=fib(10)s=‘我是分割线‘print(f.__next__())print(s.center(50,‘-‘))print(f.__next__())print(s.center(50,‘-‘))#异常捕获g=fib(10)while True: try: x = next(g) print(x) except StopIteration as e: print("Generator got en error:",e.value) break##############################################################通过yield实现在单线程的情况下实现并发运算的效果def consumer(name): print(‘%s 准备买面包啦‘%name) while True: product=yield print(‘%s 买了面包%s‘%(name,product))def producer(): c1=consumer(‘韩梅梅‘) c2=consumer(‘李雷‘) c1.__next__() c2.__next__() for i in range(10): time.sleep(1) print(‘面包%s和面包%s出炉了!‘%(i,i+1)) c1.send(i) c2.send(i+1)#producer() # 迭代器# 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。# # isinstance()判断一个对象是否是Iterable对对象# 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。# 把list、dict、str等Iterable变成Iterator可以使用iter()函数 print(isinstance(generator,Iterable))#True
时间: 2024-10-07 11:51:50