如果给一个list或者tuple,我们可以通过for循环来遍历这个列表或者元组,这种遍历就是迭代。
在python中,使用for...in 来完成迭代的。
python的for循环不仅可以用在list或者tuple上,还可以作用在其他可迭代对象上,对于有无下标,只要是可迭代对象,都可以迭代,比如dict:
>>> s = {'a':1,'b':2,'c':3}
>>> for key in s:
... print key
...
a
c
b
>>> for x,y in [(1,1),(2,4),(3,9)]:
... print x,y
...
1 1
2 4
3 9
>>> for i,value in enumerate(['A','B','C']):
... print i,value
...
0 A
1 B
2 C
>>> from collections import Iterable
>>> isinstance('abc',Iterable)
True
>>> isinstance([1,2,3],Iterable)
True
>>> isinstance(123,Iterable)
False
本文介绍了Python中的迭代概念及其应用,包括如何使用for循环遍历列表、元组、字典等可迭代对象,并展示了通过enumerate函数获取元素及其索引的方法。

被折叠的 条评论
为什么被折叠?



