python的map函数的用法

作为python的常用内置函数之一,map函数在某些场景解决问题确实方便,今天就整理一下map函数的用法。

函数官方解释

def map(function, sequence, *sequence_1): # real signature unknown; restored from __doc__
“””
map(function, sequence[, sequence, …]) -> list

Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).
“””
return []

看上去还是挺好理解的,加上一些例子就没问题了。

参数

function:一个函数

Sequence:列表

*sequence_1:多个列表

返回值

一个列表list

作用

①传入一个函数,一个列表的情况

将函数作用于列表中的每一个元素,最终返回作用后的结果列表。

相当于[function(x) for x in sequence]

②传入一个函数,多个列表的情况

取不同列表相同位置的元素,传入函数中进行处理,最终返回作用后的结果列表。

例子

①传入一个函数,一个列表的情况

上代码:

list1 = [1, 2, 3, 4]
def incre(x):
    return x+1
result_list = map(incre,list1)
print result_list

输出结果为[2, 3, 4, 5]

②结合匿名函数lambda使用

以下代码的效果和例子①是一样的:

list1 = [1, 2, 3, 4]
result_list = map(lambda x:x+1,list1)
print result_list

lambda函数,这是python的匿名函数,这里先不多说了。

③传入一个函数,多个列表的情况

先上代码:

list1 = [1, 2, 3, 4]
list2 = [2, 3, 4, 5]
list3 = [3, 4, 5, 6]
def addition(x,y,z):
    return x+y+z
result_list = map(addition,list1,list2,list3)
print result_list

输出结果是[6, 9, 12, 15]

看数字,可以感觉得出来,6=1+2+3,9=2+3+4,12=3+4+5,15=4+5+6,这个时候再看看我在上面的解释:

取不同列表相同位置的元素,传入函数中进行处理,最终返回作用后的结果列表

就比较好理解了,这相当于并行处理。

这里要注意两点:

1.传入的列表(或元组)的数目,要和函数参数的数目一致,比如例子③里面函数addition就需要三个参数,这个时候得传三个列表进去。

2.不同列表的长度要一致,且对应元素的类型要相同。

④传入None

这种情况,直接传入None作为函数,看代码:

list1 = [1, 2, 3, 4]
list2 = [2, 3, 4, 5]
result_list = map(None, list1)
print result_list
#输出结果:[1, 2, 3, 4]
result_list = map(None, list1, list2)
print result_list
#输出结果:[(1, 2), (2, 3), (3, 4), (4, 5)]

如果只传一个列表进去,那就原封不动的返回,如果传多个列表,则效果和zip()函数是一样的,返回一个大列表,里面是多个列表相同位置元素组合出来的元组。

发表评论

电子邮件地址不会被公开。 必填项已用*标注