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 = 123
for 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
<list_iterator object at 0x0000022502A679B0>
>>> I.__next__()
1
>>> I.__next__()
2
>>> I.__next__()
3
>>> I.__next__()
4
>>> I.__next__()
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
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)