import os # 导入os模块,模块的概念后面讲到
[d for d in os.listdir(‘.’)] # os.listdir可以列出文件和目录
[‘.emacs.d’, ‘.ssh’, ‘.Trash’, ‘Adlm’, ‘Applications’, ‘Desktop’, ‘Documents’, ‘Downloads’, ‘Library’, ‘Movies’, ‘Music’, ‘Pictures’, ‘Public’, ‘VirtualBox VMs’, ‘Workspace’, ‘XCode’]
for循环其实可以同时使用两个甚至多个变量,比如dict的iteritems()可以同时迭代key和value:
d = {‘x’: ‘A’, ‘y’: ‘B’, ‘z’: ‘C’ }
for k, v in d.iteritems():
… print k, ‘=’, v
…
y = B
x = A
z = C
因此,列表生成式也可以使用两个变量来生成list:
d = {‘x’: ‘A’, ‘y’: ‘B’, ‘z’: ‘C’ }
[k + ‘=’ + v for k, v in d.iteritems()]
[‘y=B’, ‘x=A’, ‘z=C’]
最后把一个list中所有的字符串变成小写:
L = [‘Hello’, ‘World’, ‘IBM’, ‘Apple’]
[s.lower() for s in L]
[‘hello’, ‘world’, ‘ibm’, ‘apple’]