05 Feb 2017
迭代是一个通用的术语,用于逐个取出对象内的元素,任何你使用循环的时候,无论显式还是隐式,都是迭代。
可迭代对象是一个拥有iter方法的对象,该方法返回一个迭代器,或者是拥有一个getitem方法的对象,该方法可以从零开始获取一个序列的索引,在索引结束后会抛出IndexError。所以,可迭代对象就是一个可以被得到迭代器的对象。
迭代器是一个拥有next(python2)或next(python3)方法的对象
>>> iter? Docstring: iter(collection) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. Type: builtin_function_or_method
iter函数可以返回可迭代对象的迭代器,可迭代对象必须含有方法(
__iter__),或者是方法(__getitem__)
# 列表本身拥有__iter__,所以可以生成迭代器对象 >>> l = [1, 2, 3] >>> iter(l) Out[13]: <listiterator at 0x7efc449135d0> >>> l.__iter__() Out[14]: <listiterator at 0x7efc448f5950> # 字符串没有__iter__,但是拥有__getitem__方法 >>> s = "abc" >>> s.__getitem__? Type: method-wrapper String form: <method-wrapper '__getitem__' of str object at 0x7efc50eca918> Docstring: x.__getitem__(y) <==> x[y] >>> iter(s) Out[20]: <iterator at 0x7efc448f5590>
# 迭代器对象拥有next方法 >>> il = iter(l) >>> il.next() Out[22]: 1 >>> il.next() Out[23]: 2 >>> il.next() Out[24]: 3 >>> il.next() --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-25-791606ca2106> in <module>() ----> 1 il.next() StopIteration: # for循环的原理就是预先取得被循环对象的迭代器,然后不断的调用next方法,直到遇到StopIteration >>> for x in l: print x 1 2 3 # 等同于for x in l.__iter__():print x