如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。
dict迭代的是key。如果要迭代value,可以用for value in d.values(), 如果要同时迭代key和value,可以用for k, v in d.items() 由于字符串也是可迭代对象,因此,也可以作用于for循环: >>> for ch in 'ABC': ... print(ch) ... A B C 如何判断一个对象是可迭代对象 from collections import Iterable >>> isinstance('abc', Iterable) # str是否可迭代 True >>> isinstance([1,2,3], Iterable) # list是否可迭代 True >>> isinstance(123, Iterable) # 整数是否可迭代 False 最后一个小问题,如果要对list实现类似Java那样的下标循环怎么办? Python内置的enumerate函数可以把一个list变成索引-元素对, 这样就可以在for循环中同时迭代索引和元素本身: >>> for i, value in enumerate(['A', 'B', 'C']): ... print(i, value) ... 0 A 1 B 2 C举个例子,要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11))
[x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100] 使用两层循环,可以生成全排列: >>> [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] import os # 导入os模块,模块的概念后面讲到 >>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录 ['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library']