1:for循环遍历
在Python中for循环可以用于遍历任何序列类型,包括列表,元组,字符串,但是不能用于遍历整数,代码如下:
# 遍历列表t = [1,2,3]for x in t: print(x) # 遍历元组t = (1,2,3,)for x in t: print(x) # 遍历字符串t = '123'for x in t: print(x) t = 123for x in t: # TypeError: 'int' object is not iterable print(x)
for循环为什么不能用于整数呢,从报错信息(TypeError: 'int' object is not iterable)可知,int 不是一个可以迭代对象,在Python中是否可迭代或者是否能够for循环遍历需要遵守Python中的迭代协议。
2:迭代协议:(包括两种对象)
可迭代对象(Iterable):里面包含了__iter__()
迭代器对象(Iterator):里面包含了__iter__() 和 __next__()
列表,字符串,元组,字典是可迭代对象,整数不是:测试代码如下
>>> lst = [1,2,3]>>> print('__iter__' in dir(lst),'__next__' in dir(lst))True False>>> s='ixusy88'>>> print('__iter__' in dir(s),'__next__' in dir(s))True False>>> s=(1,2,3,)>>> print('__iter__' in dir(s),'__next__' in dir(s))True False>>> d={'age':18}>>> print('__iter__' in dir(d),'__next__' in dir(d))True False>>> i = 100>>> print('__iter__' in dir(i),'__next__' in dir(i))False False>>>
在for循环执行过程中,Python会自动调用对象的__iter__()方法,从而返回一个迭代器对象,再使用这个迭代器对象调用__next__()方法获取序列中的一个元素,每次调用都获取下一个元素,直到结束抛出StopIteration异常。
lst = [1,2,3,4]for x in lst: print(x) I = lst.__iter__()while 1: try: x = I.__next__() except StopIteration: break print(x)
手工迭代:
>>> lst = [1,2,3,4]>>> lst[1, 2, 3, 4]>>> I = lst.__iter__()>>> I>>> I.__next__()1>>> I.__next__()2>>> I.__next__()3>>> I.__next__()4>>> I.__next__()Traceback (most recent call last): File "", line 1, in I.__next__()StopIteration>>> print('__iter__' in dir(I),'__next__' in dir(I))True True>>>
3:自定义迭代器
# 斐波那契函数# class Fibonacci: def __init__(self,n): self.a = 0 self.b = 1 self.max_cnt = n def __next__(self): self.a, self.b = self.b, self.a+self.b if self.a > self.max_cnt: raise StopIteration return self.a def __iter__(self): return self fib = Fibonacci(100)print(fib) for x in fib: print(x) print('*'*30) for x in Fibonacci(200): print(x)