3-1介绍可迭代对象和迭代器对象

>>> l = [1,2,3,4,5] >>> s = '12345' >>> iter(l) <listiterator object at 0x02A82E50> >>> iter(s) <iterator object at 0x02BB7A90> >>> iter(5) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> iter(5) TypeError: 'int' object is not iterable >>>
L列表对象,s字符串对象,都是可迭代的对象。Iter(l)或iter(s)为迭代器对象。Iter(5)会抛出异常,因为5是不可迭代的对象。
>>> l.__iter__ <method-wrapper '__iter__' of list object at 0x02BBB0F8>
__iter__()接口就是迭代的标准接口如对象没有__iter__()接口有__getitem__()序列接口也可以。iter(l)实际调用的是 l.__iter__()。
>>> help(iter) Help on built-in function iter in module __builtin__: iter(...) 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.
使用此方法,支付自身的迭代器或是一个序列。
#t为迭代器对象,只有一个接口next()接口,列表都迭代完时,会抛出一个异常。
>>> t = iter(l) >>> t.next() 1 >>> t.next() 2 >>> t.next() 3 >>> t.next() 4 >>> t.next() 5 >>> t.next() Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> t.next() StopIteration
>>>for x in l : print x
for循环的机制,就是从列表l中得到迭代器,不断执行next(),直到捕获到StopIteration异常后,跳出循环。
posted on 2018-04-12 09:31 石中玉smulngy 阅读(219) 评论(0) 收藏 举报
浙公网安备 33010602011771号