参考:
1.1 迭代(iteration)
迭代:使用for循环遍历所有元素
在c中
for (i=0; i<length; i++) {
n = list[i];
}
在python中
list1 = [4,5,6,7,8,9]
for each in list1:
print(each)
1.2 可迭代对象
能够执行上述迭代操作(遍历所有元素)的对象就是可迭代对象
如何判断一个对象是可迭代对象?
通过collections.abc
模块的Iterable
类型判断
from collections.abc import Iterable
isinstance([4,5,6,7],Iterable)
#True
python中哪些对象是可迭代对象?
含有 __iter__()
方法或 __getitem__()
方法的对象称之为可迭代对象
1.3 迭代器
执行可迭代对象的 __iter__
方法就能得到一个 迭代器,
list1 = [4,5,6,7,8]
it1 = list1.__iter__()#得到一个迭代器
it1
# <list_iterator object at 0x0000019667BA73A0>
并且这个迭代器会有一个 __next__
方法。
执行 __next__
方法来使用迭代器
it1.__next__()
#4
it1.__next__()
#5
it1.__next__()
#6
it1.__next__()
#7
it1.__next__()
#8
it1.__next__()
#Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
it1.__next__()
StopIteration
调用迭代器的 __next__()
取值的时候,已经被取出的值不会再次取出,迭代器是有状态的,能够记住状态,从上一次结束的地方再开始
也可以使用python内置的iter方法和next方法
list2 = [1,2,3,4,5]
it2 = iter(list2)
it2
#<list_iterator object at 0x0000019667BA7430>
next(it2)
#1
next(it2)
#2
next(it2)
#3
next(it2)
#4
next(it2)
#5
next(it2)
#Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
next(it2)
StopIteration
多次执行iter返回的迭代器对象是不同的
list1 = [4,5,6,7,8]
it11 = list1.__iter__()
it12 = list1.__iter__()
it11
#<list_iterator object at 0x0000019667BA7400>
it12
#<list_iterator object at 0x0000019667BA6EF0>
list2 = [1,2,3,4,5]
it21 = iter(list2)
it22 = iter(list2)
it21
#<list_iterator object at 0x0000019667BA6E00>
it22
#<list_iterator object at 0x0000019667BA6EC0>
it11==it12
#False
it21==it22
#False
可迭代的对象和迭代器之间的关系是:Python 从可迭代的对象 中获取迭代器。