迭代器:

迭代器是访问集合内元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素都被访问一遍后结束。

迭代器不能回退,只能往前进行迭代。这并不是什么很大的缺点,因为人们几乎不需要在迭代途中进行回退操作。

对于原生支持随机访问的数据结构(如tuple、list),迭代器和经典for循环的索引访问相比并无优势,反而丢失了索引值(可以使用内建函数 enumerate()找回这个索引值,这是后话)。但对于无法随机访问的数据结构(比如set)而言,迭代器是唯一的访问元素的方式。


'''

iter() Definition :iter(collection)


Get an iterator from anobject. In the first form,

the argument must supplyits own iterator, or be a sequence.

In the second form, thecallable is called until it returns the sentinel.


结果:表示迭代完成!

>>> it.next()

Traceback (most recentcall last):

File "", line 1, in

StopIteration


'''

#例子1:

lst=range(2)

lst

it=iter(lst)

it

it.next()

it.next()

it.next()

it.next()








例子2:

lst=range(2)

it=iter(lst)

try:

while True:

val=it.next()

print val

except StopIteration:

pass


10-04 22:11