python的map和zip操作
阿新 • • 發佈:2019-02-09
如果要將一個string list轉換成int list (list裡每個string都轉成int),比如
['0','1','2'] -> [0,1,2]
可以使用:
[int(x) for x in list]
或者使用map操作: map(func, list) 對list裡的每個元素apply func.
map(int, list)
假設有一個2維陣列(用list實現):
list = [[0,1,2],[3,1,4]]
如果要得到每行之和,可以用以下兩種方式:
>>> 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個元素:
>>> 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的:
>>> 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]