3-1 如何实现可迭代对象和迭代器对象
先看看如何遍历list的
la = [1,2,3]
for x in la: ==>其实是先取得iterator,然后调用iterator.next()
print x
如下是for循环的迭代的过程
>>> la = [1,2,3]
>>> iterator1 = iter(la)
>>> iterator1.next()
1
>>> iterator1.next()
2
>>> iterator1.next()
3
>>> iterator1.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
iter帮助信息
iterable 可迭代对象 list str 都
iterator 迭代器
list 有一个iter方法
str 有一个getitem方法
可迭代对象 只要有iter 或者 getitem都是可迭代对象
迭代器对象 next()
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.
(END)
print iter(l) = l__iter__()
print iter(s) = l__getitem__()
dir(iter(l) 迭代器对象
[‘class‘, ‘delattr‘, ‘doc‘, ‘format‘, ‘getattribute‘, ‘hash‘, ‘init‘, ‘iter‘, ‘length_hint‘, ‘new‘, ‘reduce‘, ‘reduce_ex‘, ‘repr‘, ‘setattr‘, ‘sizeof‘, ‘str‘, ‘subclasshook‘, ‘next’]