# iter函数
s = "I love You"
print(isinstance(s,Iterable))
print(isinstance(s,Iterator))
s_iter = iter(s)
print(isinstance(s_iter,Iterable))
print(isinstance(s_iter,Iterator))
True
False
True
True
生成器,
generator : 一边循环一边计算下一个元素的机制/算法
需要满足三个条件
每次调用都生产出for 循环需要的下一个元素
如果达到最后一个后,爆出StopIteration异常
可以被next函数调用
如何生成一个生成器
直接使用
如果函数中包含yield,则这个函数就叫做生成器
next 调用函数,遇到yield返回
# 直接使用生成器
L = [x*x for x in range(5)] # 放在中括号中的列表生成器
g = (x*x for x in range(5)) # 放在小括号中的就是生成器
print(type(L))
print(type(g))
<class 'list'>
<class 'generator'>
# 函数案例# 在函数odd中,yield负责返回defodd():
print("Step 1")
yield1
print("Step 2")
yield2
print("Step 3")
yield3# odd()是调用生成器,通过next进行调用
g = odd()
one = next(g)
print(one)
two = next(g)
print(two)
three = next(g)
print(three)
Step 1
1
Step 2
2
Step 3
3
# 通过for 循环调用生成器# 斐波那契数列生成器deffib(max):
n,a,b = 0,0,1while n < max:
yield b
a,b = b, a+b
n += 1return'Done'
g = fib(5)
for i in range(6):
rst = next(g)
print(rst)
1
1
2
3
5
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-14-526d3727af54> in <module>()
11
12 for i in range(6):
---> 13 rst = next(g)
14 print(rst)
StopIteration: Done
ge = fib(10)
""",
生成器的典型用法是在for 循环中使用,
比较常用的典型生成器就是range,
"""for i in ge:
print(i)
# 案例2协程的状态defsimple_coroutine(a):
print("-> start")
b = yield a
print("-> recived",a,b)
c = yield a + b
print("-> recived",a,b,c)
# runs
sc = simple_coroutine(5)
aa = next(sc)
print(aa)
bb = sc.send(6)
print(bb)
cc = sc.send(7)
print(cc)