零基础学python之迭代器

迭代器
迭代器可以简单地理解为 for 循环, Python 除了 for 循环为我们准备了另一种访问集合元素的方式。
特点:
记住遍历位置的对象。
迭代器从集合的第一个元素开始访问,直到所有元素结束。
迭代器只能前进,不能后退。
但要判断一个对象是否有迭代器,除了看它是否可以使用 for 循环外, Python 它还为我们提供了更专业的方法—— isinstance() 。
我们能用 isinstance() 判断当前对象是否可以迭代。
在使用迭代器之前,需要引入迭代器,因为迭代器不是 Python 内置方法。
fromcollections.abcimportIterable
print(isinstance('geekdigging',Iterable))
print(isinstance([],Iterable))
print(isinstance([],Iterable))
print(isinstance({xforxinrange(5)},Iterable))
print(isinstance(123,Iterable))打印结果如下:
True True True True False
这里有一点要注意,当我们介绍的时候 Iterable 在之前的版本介绍中,都是 from collections import Iterable ,但是在 Python3.7 抛出一个异常,如下:
D:/Development/Projects/python-learning/base-iter/Demo.py:1:DeprecationWarning:UsingorimportingtheABCs from' collections'insteadoffrom'collections.abc'isdeprecated,andin3.8itwillstopworking fromcollectionsimportIterable
意思是,这种引入方式将被引入 Python3.8 停止使用,现在 Python3.8 已发布,我们将按照提示中的方式进行介绍和使用 from collections.abc import Iterable 。
迭代器中最重要的方法必须是 next() ,从名字上可以看出,它的作用是下一个。
现在让我们试着迭代一个列表:
list1=[1,2,3,4] next(list1)
执行结果:
Traceback(mostrecentcalllast): File"D:/Development/Projects/python-learning/base-iter/Demo.py",line12,in<module> next(list1) TypeError:'list'objectisnotaniterator
不是说好的列表可以迭代,为什么又报错了?
这位同学,先消气,看错信息说了什么,这是在提醒我们列表不是迭代器。
因此,可迭代对象不一定是迭代器!
我们导入 Iterator 模块,先将列表转换成迭代器,再试试。
list1=iter(list1) print(type(list1)
执行结果:
<class'list_iterator'>
就类型而言,它现在是一个可迭代的列表。让我们再试一次 next() 方法。
print(next(list1) print(next(list1) print(next(list1) print(next(list1)
执行结果:
1 2 3 4
你看,现在可以正常打印了。
刚才我们迭代了整个列表中的元素。如果我们在这个时候再次迭代会发生什么?
print(next(list1)
执行结果:
Traceback(mostrecentcalllast): File"D:/Development/Projects/python-learning/base-iter/Demo.py",line23,in<module> print(next(list1) StopIteration
如果你看到了,你会把它扔出去 StopIteration 的异常。
也许在这里,你仍然觉得迭代器没用。让我再举一个例子。如果我们现在有一个, set 集合,我想一个接一个地得到 set 这时,迭代器就派上用场了,因为它是 set 集合中没有索引。如果你想得到一定的值,你只能使用它 for 循环整个集合,但有了迭代器,我们就不需要循环整个集合了。
set1={1,2,3,4,5}
set1=iter(set1)
print(next(set1)
print(next(set1)
print(next(set1)
print(next(set1)
print(next(set1)结果我就不放了,大家应该都知道结果了。
此外,迭代器有一个很大的优势,那就是在迭代之前,所有的元素都不需要准备好。迭代器只有在迭代到某个元素时才开始计算该元素。在此之前或之后,元素不能存在或被销毁。
这一特点使其在一些巨大的集合中具有很大的优势。
