python学习笔记之map和zip的使用

map函数:

map(functioniterable...)

  Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed,function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

  map接收一个函数和一个可迭代对象(如列表)作为参数,用函数处理每个元素,然后返回新的列表。

举个例子:

def sumfunc(*args):
	sum=0
	for i in args:
		sum+=i
	return sum

if __name__=="__main__":
	list=[(1,2),(3,4)]
	print map(sumfunc,*list)

结果是:[4, 6]

如果我们想把(1,2)作为参数调用sumfunc,怎么办呢,我的方法是就是使用zip

def sumfunc(*args):
	sum=0
	for i in args:
		sum+=i
	return sum

if __name__=="__main__":
	list=[(1,2),(3,4)]
	print map(sumfunc,*zip(*list))
zip有点类似于把原来的矩阵的行作为列(好像是数学里叫转置矩阵?),

|1,2|   --》|1 , 3|

|3,4|   --》|2 , 4|

如果是一个n x n 的矩阵,转换的时候就以最短的为标准,所以当使用上面的(zip)方法,必须使得列表每一项的长度一致

即,如果 list=[(1,2),(3,4,5,6,7)] ,当使用zip的时候,也就相当于看成list=[(1,2),(3,4)]

这样就能得到我门想要的,

还有另外一种处理方法,就是要在函数内部做一点处理:

def sumfunc(*args):
	sum=0
	if isinstance(args[0],Tuple):
		list = Tuple(*args[0])
	else:
		list=Tuple(*args)
	for num in list:
		sum+=num
	return sum
if __name__=="__main__":
	print sumfunc(1,2,3,4)
	list=[(1,2,3),(3,4,5,5)]
	print map(sumfunc,list)


其实也可以用for来代替,而且我个人感觉更好理解一点:

if __name__=="__main__":
	list=(1,2,3),(3,4,5,5)]
	print [sumfunc(*args) for args in list]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值