In [1]: myTuple=('123','xsd','zsdf')
In [2]: i=iter(myTuple)
In [3]: i.next()
Out[3]: '123'
In [4]: i.next()
Out[4]: 'xsd'
In [5]: i.next()
Out[5]: 'zsdf'
In [6]: i.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
C:\Users\bill\<ipython-input-6-e590fe0d22f8> in <module>()
----> 1 i.next()
StopIteration:
迭代器就是有一个next()方法的对象 ,像上述的一样。
列表迭代:
Out[10]: [12, 23, 34, 56]
In [11]: for j in i:
....: print j
....:
12
23
34
56
字典迭代:字典的迭代器会迭代字典所有的key,即
In [12]: for eachKey in Dict.keys()
In [13]: for eachKey in Dict
上述2种方式等价
字典迭代还有其他方式 :
In [16]: for i in myDict.itervalues():
....: print i
....:
23
123
sdfhsf
In [17]: for i in myDict.iteritems():
....: print i
....:
('sdf', 23)
('123', 123)
('sdsf', 'sdfhsf')
In [18]: for i in myDict.iterkeys():
....: print i
....:
sdf
123
sdsf
文件迭代器会自动跳用readline()方法,循环所有行。
列表解析: