Python advanced features-list generation, python feature list
Overview
[x *x for x in range(1,11)]
[k+'='+v for k,v in d.items()]
[s.lower() for s in L]
1. Single-layer Iteration
>>> [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. Double-Layer for Loop
>>> [m+n for m in 'abc' for n in 'cde']['ac', 'ad', 'ae', 'bc', 'bd', 'be', 'cc', 'cd', 'ce']
3. list file and directory names
>>> 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. dictionary Iteration
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }>>> for k,v in d.items():... print k,'=',v... y = Bx = Az = C
>>> D = {'X': 'A', 'y': 'B', 'z': 'C '}
>>> [K + '=' + v for k, v in d. items ()]
['Y = B ', 'X = A', 'z = C']
5. the string is changed to lowercase.
>>> L = ['Hello', 'World', 'IBM', 'Apple']>>> [s.lower() for s in L]['hello', 'world', 'ibm', 'apple']