##迭代器:是访问集合内元素的一种方式,用来for遍历数据,与下标方式的访问数据不一样,不能往回访问数据 ,提供了一种惰性方式数据的访问
#Iterable可迭代 __iter__ Iterator(Iterable) 迭代器 __iter__ __next__
from collections.abc import Iterable,Iterator
a=[]
print(isinstance(a,Iterable))##True
print(isinstance(a,Iterator))##False
def fib(index):
a= 1 if index<2 else fib(index-1)+fib(index-2)
return a
print(fib(10))##89
def gen_fib(index):
a,b,c=0,0,1
while a<index:
yield b+c
b,c=c,c+b
a+=1
for a in gen_fib(10):
print(a)
def gen_fun():
yield 1
name="howhy"
yield 2
age=20
return "end"
import dis
genfun=gen_fun()
print(dis.dis(genfun))
print(genfun.gi_frame.f_lasti)
print(genfun.gi_frame.f_locals)
next(genfun)
print(genfun.gi_frame.f_lasti)
print(genfun.gi_frame.f_locals)
next(genfun)
print(genfun.gi_frame.f_lasti)
print(genfun.gi_frame.f_locals)
23 0 LOAD_CONST 1 (1)
2 YIELD_VALUE
4 POP_TOP
24 6 LOAD_CONST 2 ('howhy')
8 STORE_FAST 0 (name)
25 10 LOAD_CONST 3 (2)
12 YIELD_VALUE
14 POP_TOP
26 16 LOAD_CONST 4 (20)
18 STORE_FAST 1 (age)
27 20 LOAD_CONST 5 ('end')
22 RETURN_VALUE
None
-1
{}
2
{}
12
{'name': 'howhy'}