首頁  >  文章  >  後端開發  >  python中map()與zip()操作方法介紹

python中map()與zip()操作方法介紹

高洛峰
高洛峰原創
2017-03-07 16:11:031646瀏覽

對於map()它的原型是:map(function,sequence),就是對序列sequence中每個元素都執行函數function操作。

例如之前的a,b,c = map(int,raw_input().split()),意思是說把輸入的a,b,c轉換成整數。再例如:

a = ['1','2','3','4']
print map(list,a)
print map(int,a)

第一個map是把列表a中每個元素轉換成列表,第二個map就是把a中每個元素轉化為整數。
而對於zip(),原型是zip(*list),list是一個列表,zip(*list)返回的是一個元組,例如:

list = [[1,2,3],[4,5,6],[7,8,9]]
t = zip(*list)
print t

輸出:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

x = [1,2,3,4,5]
y = [6,7,8,9,10]
a = zip(x,y)
print a

#輸出:[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

#以下是一些補充:

[python] 
>>> list = [[0,1,2],[3,1,4]] 
>>> [sum(x) for x in list] 
[3, 8] 
>>> map(sum,list) 
[3, 8]

如果要得到每列之和,需要用zip(*list)先unzip list,得到一個元組list,其中第i個元群組包含了每行的第i個元素:

[python] 
>>> list = [[0,1,2],[3,1,4]] 
>>> zip(*list) 
[(0, 3), (1, 1), (2, 4)] 
>>> [sum(x) for x in zip(*list)] 
[3, 2, 6] 
>>> map(sum,zip(*list)) 
[3, 2, 6]

#下面的例子是關於zip和unzip(其實是zip和*一起用)如何work的:

[python] 
>>> x=[1,2,3] 
>>> y=[4,5,6] 
>>> zipped = zip(x,y) 
>>> zipped 
[(1, 4), (2, 5), (3, 6)] 
>>> x2,y2=zip(*zipped) 
>>> x2 
(1, 2, 3) 
>>> y2 
(4, 5, 6) 
>>> x3,y3=map(list,zip(*zipped)) 
>>> x3 
[1, 2, 3] 
>>> y3 
[4, 5, 6]


#更多python中map()與zip()操作方法介紹相關文章請關注PHP中文網!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn