python的map()函数

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

map() 函数语法:

map(function, iterable1,iterable2 ...)

function -- 函数,有两个参数

iterable -- 一个或多个序列

1.求一个列表的平方

list1 = [1,2,3,4,5,6,7,8,9]
def foo(x):
    return x*x

c=list(map(foo,list1))
print(c)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
求三个列表的乘积
list1 = [1,2,3,4,5,6,7,8,9]
list2 = [1,2,3,4,5,6,7,8,9]
list3 = [9,8,7,6,5,4,3,2,1]
def fun(x,y,z):
    return x*y*z
d=list(map(fun,list1,list2,list3))
print(d)
[9, 32, 63, 96, 125, 144, 147, 128, 81]
用lambda求两个列表之和
a = [1,2,3]
b = [4,5,6]
c=map(lambda x,y:x + y,a,b)
for i in c:
    print(i,end=' ')
5 7 9



猜你喜欢

转载自blog.51cto.com/853056088/2155134