区别可迭代对象和迭代器
1、判断是否可以迭代
from collections import Iterable
def fid(times):
n = 0
a , b = 0,1
while n < times:
yield b
a,b = b , a+b
n += 1
return 'done'
F = fid(10)
A = []
B = "asd"
print(isinstance(A,Iterable))
print(isinstance(B,Iterable))
print(isinstance(F,Iterable))
结果:
均为True
总结:凡是可以作用于for循环的对象都是Iterable类型,即可迭代对象
2、迭代器
from collections import Iterator def fid(times): n = 0 a , b = 0,1 while n < times: yield b a,b = b , a+b n += 1 return 'done' F = fid(10) A = [] B = "asd" print(isinstance(A,Iterator)) print(isinstance(B,Iterator)) print(isinstance(F,Iterator))
结果:
False
False
True
总结:凡是可以作用于next()函数的对象都是Iterator类型,也就是迭代器
3、可迭代对象转换为迭代器,iter()函数
from collections import Iterator def fid(times): n = 0 a , b = 0,1 while n < times: yield b a,b = b , a+b n += 1 return 'done' F = fid(10) A = [] B = "asd" print(isinstance(iter(A),Iterator)) print(isinstance(iter(B),Iterator)) print(isinstance(F,Iterator))
结果:
均为True
总结,可迭代类型可通过iter()函数获得一个迭代器
可迭代对象Iterable和迭代器Iterator最大的区别在于是否可作用于next()函数,它们均可作用于for循环