python列表推導式
阿新 • • 發佈:2017-10-04
lai com expr 實際應用 http port ack ron dig
python基礎——列表推導式
1 列表推導式定義
列表推導式能非常簡潔的構造一個新列表:只用一條簡潔的表達式即可對得到的元素進行轉換變形
2 列表推導式語法
基本格式如下:
[expr for value in collection if condition]
過濾條件可有可無,取決於實際應用,只留下表達式
列表推導式例子:
1 2 |
l = [ "egg%s" % i for i in range ( 10 )]
print (l)
|
類似於這段for代碼:
1 2 3 4 |
egg_list = []
for i in range ( 10 ):
egg_list.append( "egg%s" % i)
print (egg_list)
|
列表推導式還可以加更多的if判斷for循環
1 2 3 4 |
l = [ ‘egg%s‘ % i for i in range ( 1 , 101 )]
l = [ ‘egg%s‘ % i for i in range ( 1 , 101 ) if i > 50 ]
l = [ ‘egg%s‘ % i for i in range ( 1 , 101 ) if i > 50 if i< 60 ]
print (l)
|
3 列表推導式優點
方便,改變了編程習慣,屬於聲明式編程
舉例:
1 2 3 4 |
l = [ 1 , 2 , 3 , 4 ]
s = "hello"
l1 = [(num,i) for num in l for i in s]
print (l1)
|
輸出結果為:
1 |
[( 1 , ‘h‘ ), ( 1 , ‘e‘ ), ( 1 , ‘l‘ ), ( 1 , ‘l‘ ), ( 1 , ‘o‘ ), ( 2 , ‘h‘ ), ( 2 , ‘e‘ ), ( 2 , ‘l‘ ), ( 2 , ‘l‘ ), <br>( 2 , ‘o‘ ), ( 3 , ‘h‘ ), ( 3 , ‘e‘ ), ( 3 , ‘l‘ ), ( 3 , ‘l‘ ), ( 3 , ‘o‘ ), ( 4 , ‘h‘ ), ( 4 , ‘e‘ ), ( 4 , ‘l‘ ), <br>( 4 , ‘l‘ ), ( 4 , ‘o‘ )]
|
這個列表推導式相當於:
1 2 3 4 5 6 7 8 |
l = [ 1 , 2 , 3 , 4 ]
s = "hello"
l1 = []
for num in l:
for i in s:
t = (num,i)
l1.append(t)
print (l1)
|
4 列表表達式例子
1 2 3 4 5 6 7 8 9 10 11 |
import os
g = os.walk( "C:\python_fullstack_wen\day24\wen" )
file_path_list = []
for i in g:
for j in i[ - 1 ]:
file_path_list.append( "%s\\%s" % (i[ 0 ],j))
print (file_path_list)
g = os.walk( "C:\python_fullstack_wen\day24\wen" )
file_path_list = [ "%s\\%s" % (i[ 0 ],j) for i in g for j in i[ - 1 ]]
print (file_path_list)
|
輸出結果:
1 2 |
[ ‘C:\\python_fullstack_wen\\day24\\wen\\yan1.txt‘ , ‘C:\\python_fullstack_wen\\day24\\wen\\wen1<br>\\yan1.txt‘ , ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\jie1\\yan1.txt‘ , <br> ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\yan1\\yan1.txt‘ , <br> ‘C:\\python_fullstack_wen\\day24\\wen\\wen2\\yan2.txt‘ ]
[ ‘C:\\python_fullstack_wen\\day24\\wen\\yan1.txt‘ , ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\yan1.txt‘ , ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\jie1\\yan1.txt‘ , ‘C:\\python_fullstack_wen\\day24\\wen\\wen1\\yan1\\yan1.txt‘ , ‘C:\\python_fullstack_wen\\day24\\wen\\wen2\\yan2.txt‘ ]
|
python列表推導式