python中map()与zip()操作方法

yipeiwu_com5年前Python基础

对于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数据类型之Number数字操作实例详解

本文实例讲述了Python数据类型之Number数字操作。分享给大家供大家参考,具体如下: 一、Number(数字) 数据类型 为什么会有不同的数据类型? 计算机是用来做数学计算的机器,...

python中pygame模块用法实例

python中pygame模块用法实例

本文实例讲述了python中pygame模块用法,分享给大家供大家参考。具体方法如下: import pygame, sys from pygame.locals import *...

浅谈python实现Google翻译PDF,解决换行的问题

浅谈python实现Google翻译PDF,解决换行的问题

我们复制PDF到Google翻译时,总是会出现换行的情况,如果自己手动去除,那就太麻烦了。 那么用Python就可以解决,复制到粘贴板以后,Python程序自动可以把\n换成空格,然后...

python3.x 将byte转成字符串的方法

如下所示: result = str(要转换的变量名, encoding='utf-8') 例如: result = str(request, encoding='utf-8'...

django-rest-swagger的优化使用方法

如下所示: requirements.txt django==1.10.5 djangorestframework==3.5.3 django-rest-swagger==2.1...