推導(dǎo)式是Python中很強大的、很受歡迎的特性,具有語言簡潔,速度快等優(yōu)點。推導(dǎo)式包括:
1.列表推導(dǎo)式
2.字典推導(dǎo)式
3.集合推導(dǎo)式
嵌套列表推導(dǎo)式
NOTE: 字典和集合推導(dǎo)是最近才加入到Python的(Python 2.7 和Python 3.1以上版). 下面簡要介紹下:
【列表推導(dǎo)式】
列表推導(dǎo)能非常簡潔的構(gòu)造一個新列表:只用一條簡潔的表達式即可對得到的元素進行轉(zhuǎn)換變形
其基本格式如下:
代碼如下:
[expr for value in collection ifcondition]
過濾條件可有可無,取決于實際應(yīng)用,只留下表達式;相當(dāng)于下面這段for循環(huán):
代碼如下:
result = []
for value in collection:
if condition:
result.append(expression)
例1: 過濾掉長度小于3的字符串列表,并將剩下的轉(zhuǎn)換成大寫字母
代碼如下:
>>> names = ['Bob','Tom','alice','Jerry','Wendy','Smith']
>>> [name.upper() for name in names if len(name)>3]
['ALICE', 'JERRY', 'WENDY', 'SMITH']
例2: 求(x,y)其中x是0-5之間的偶數(shù),y是0-5之間的奇數(shù)組成的元祖列表
代碼如下:
>>> [(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
例3: 求M中3,6,9組成的列表
代碼如下:
>>> M = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [row[2] for row in M]
[3, 6, 9]
#或者用下面的方式
>>> [M[row][2] for row in (0,1,2)]
[3, 6, 9]
例4: 求M中斜線1,5,9組成的列表
代碼如下:
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [M[i][i] for i in range(len(M))]
[1, 5, 9]
例5: 求M,N中矩陣和元素的乘積
代碼如下:
>>> M = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> N = [[2,2,2],
... [3,3,3],
... [4,4,4]]
>>> [M[row][col]*N[row][col] for row in range(3) for col in range(3)]
[2, 4, 6, 12, 15, 18, 28, 32, 36]
>>> [[M[row][col]*N[row][col] for col in range(3)] for row in range(3)]
[[2, 4, 6], [12, 15, 18], [28, 32, 36]]
>>> [[M[row][col]*N[row][col] for row in range(3)] for col in range(3)]
[[2, 12, 28], [4, 15, 32], [6, 18, 36]]
新聞熱點
疑難解答
圖片精選