# 直接使用生成器
l =[x*x for x inrange(5)]#放在中括号里边是列表生成器
g =(x*x for x inrange(5))#放在小括号里边就是生成器print(type(l))print(type(g))
<class 'list'>
<class 'generator'>
#函数案例defodd():print("aa")yield1print("bb")yield2print("cc")yield3returnNone#odd()是调用生成器
f = odd()
o =next(f)print(o)
s =next(f)print(s)
t =next(f)print(t)
aa
1
bb
2
cc
3
#for循环调用生成器deffib(max):
n, a, b =0,0,1while n <max:print(b)
a,b = b, a+b
n+=1return"Done"
fib(5)
1
1
2
3
5
'Done'
#斐波那契数列的shengdeffib(max):
n, a, b =0,0,1while n <max:yield b
a,b = b, a+b
n+=1return"Done"
q = fib(5)for i inrange(6):
w =next(q)print(w)
1
1
2
3
5
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-25-fc7a341a05c9> in <module>()
9 q = fib(5)
10 for i in range(6):
---> 11 w = next(q)
12 print(w)
StopIteration: Done
#协程的状态defsimple_coroutine(a):print('-> start')
b =yield a
print('-> recived', a, b)
c =yield a + b
print('-> recived', a, b, c)# runc
sc = simple_coroutine(5)
aa =next(sc)print(aa)
bb = sc.send(6)# 5, 6print(bb)
cc = sc.send(7)# 5, 6, 7print(cc)
迭代器可迭代(iterable):直接作用于for循环的变量迭代器(iterator):不但可以直接作用于for循环,还可以被next调用list是典型的可迭代对象,不是迭代器通过isinstance判断iterable和iterator可以转换通过iter函数可以转换#可迭代l = [i for i in range(1,10)]for i in l: pri...