跟老齐学Python之让人欢喜让人忧的迭代

2019-10-05 16:50:37丽君

i
w
s
i
r
Traceback (most recent call last):      #读取到最后一个之后,报错,停止循环
  File "<stdin>", line 2, in <module>
StopIteration
>>>

首先了解一下上面用到的那个内置函数:iter(),官方文档中有这样一段话描述之:


iter(o[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

大意是说...(此处故意省略若干字,因为我相信看此文章的看官英语水平是达到看文档的水平了,乳沟没有,也不用着急,找个词典什么的帮助一下。)

尽管不翻译了,但是还要提炼一下主要的东西:

返回值是一个迭代器对象
参数需要是一个符合迭代协议的对象或者是一个序列对象
next()配合与之使用
什么是“可迭代的对象”呢?一般,我们常常将哪些能够用for来一个一个读取元素的对象,就称之为可迭代的对象。那么for也就被称之为迭代工具。所谓迭代工具,就是能够按照一定顺序扫描迭代对象的每个元素(按照从左到右的顺序),显然,除了for之外,还有别的可以称作迭代工具,比如列表解析,in来判断某元素是否属于序列对象等。

那么,刚才介绍的iter()的功能呢?它与next()配合使用,也是实现上述迭代工具的作用。在python中,甚至在其它的语言中,迭代这块的说法比较乱,主要是名词乱,刚才我们说,那些能够实现迭代的东西,称之为迭代工具,就是这些迭代工具,不少程序员都喜欢叫做迭代器。当然,这都是汉语翻译,英语就是iterator。

看官看上面的所有例子会发现,如果用for来迭代,当到末尾的时候,就自动结束了,不会报错。如果用iter()...next()迭代,当最后一个完成之后,它不会自动结束,还要向下继续,但是后面没有元素了,于是就报一个称之为StopIteration的错误(这个错误的名字叫做:停止迭代,这哪里是报错,分明是警告)。

看官还要关注iter()...next()迭代的一个特点。当迭代对象lst_iter被迭代结束,即每个元素都读取一边之后,指针就移动到了最后一个元素的后面。如果再访问,指针并没有自动返回到首位置,而是仍然停留在末位置,所以报StopIteration,想要再开始,需要重新再入迭代对象。所以,列位就看到,当我在上面重新进行迭代对象赋值之后,又可以继续了。这在for等类型的迭代工具中是没有的。