python学习笔记(6)-高级特性(二)-迭代

来源:互联网 发布:淘宝假货改进 编辑:程序博客网 时间:2024/05/22 02:09

    如果给一个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



0 0
原创粉丝点击