python高级特性-列表生成

 概述

[x *x for x in range(1,11)]
[k+'='+v for k,v in d.items()]
[s.lower() for s in L]

详解

1.单层迭代

>>> [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循环

>>> [m+n for m in 'abc' for n in 'cde']
['ac', 'ad', 'ae', 'bc', 'bd', 'be', 'cc', 'cd', 'ce']

3.列出文件和目录名

>>> 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', '\xef\xbc\x81', '.bash_history', 'install.log.syslog', '.bash_profile', 'X_solr2.0.1_20170607.tar.gz', '.viminfo']

4.字典迭代

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k,v in d.items():
...      print k,'=',v
... 
y = B
x = A
z = C

 >>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
 >>> [k+'='+v for k,v in d.items()]
 ['y=B', 'x=A', 'z=C']

5.所以字符串变成小写

>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']

 

posted @ 2017-09-06 11:23  姚红  阅读(307)  评论(0编辑  收藏  举报