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

yipeiwu_com6年前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生成带有表格的图片实例

python生成带有表格的图片实例

因为工作中需要,需要生成一个带表格的图片 例如: 直接在html中写一个table标签,然后单独把表格部分保存成图片 或者是直接将excel中的内容保存成一个图片 刚开始的思路,是直接生...

python中for循环把字符串或者字典添加到列表的方法

python中for循环把字符串或者字典添加到列表的方法

python中如何for循环把字符串添加到列表? 实例: 1.单个字符串用for循环添加到列表中: # 把L1中的字符串添加到列表alist里面 L1 = 'MJlifeBlog'...

Python操作配置文件ini的三种方法讲解

python 操作配置文件ini的三种方法 方法一:crudini 命令 说明 crudini命令是Linux下的一个操作配置文件的命令工具 用法 crudini --set [--...

python MNIST手写识别数据调用API的方法

python MNIST手写识别数据调用API的方法

MNIST数据集比较小,一般入门机器学习都会采用这个数据集来训练 下载地址:yann.lecun.com/exdb/mnist/ 有4个有用的文件: train-images-idx3...

Python 生成一个从0到n个数字的列表4种方法小结

我就废话不多说了,直接上代码吧! 第一种 def test1(): l = [] for i in range(1000): l = l + [i] 第二种(app...