概述
代码语言:javascript
复制[x *x for x in range(1,11)]
[k '=' v for k,v in d.items()]
代码语言:javascript
复制[s.lower() for s in L]
详解
1.单层迭代
代码语言:javascript
复制>>> [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]
2.双层for循环
代码语言:javascript
复制>>> [m n for m in 'abc' for n in 'cde']
['ac', 'ad', 'ae', 'bc', 'bd', 'be', 'cc', 'cd', 'ce']
3.列出文件和目录名
代码语言:javascript
复制>>> import os
>>> [d for d in os.listdir('.')]
['X_face1.3.2_20170505_qywp', 'X_solr2.0.1_20170607', 'X_media_20170524', 'install.log', 'X_LK_client1.0_20151031', '.mysql_history', 'X_LK_server1.3.0_20160906', 'X_sea2.1.0.20170622_qywp.tar.gz', 'X_fish2.3.16_170414_18110A.tar.gz', '.config', 'anaconda-ks.cfg', 'X_LK_client1.0_20151031.tar.gz', 'X_fish2.3.16_170414_18110', 'X_face1.3.2_20170505_qywp.tar.gz', 'X_LK_server1.3.0_20160906.tar.gz', 'X_sea2.1.0.20170622_qywp', '.tcshrc', '.cshrc', 'X_media_20170524.tar.gz', '.bashrc', '.bash_logout', 'xefxbcx81', '.bash_history', 'install.log.syslog', '.bash_profile', 'X_solr2.0.1_20170607.tar.gz', '.viminfo']
4.字典迭代
代码语言:javascript
复制>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k,v in d.items():
... print k,'=',v
...
y = B
x = A
z = C
5.所以字符串变成小写
代码语言:javascript
复制>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']