map()

map()原型是:map(function,sequence),就是对序列sequence中每个元素都执行函数function操作

得到每行只和:

>>> 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]

 

posted @ 2017-06-09 20:11  孙连城  阅读(247)  评论(0编辑  收藏  举报