- map()函数接收两种类型的参数,第一个参数为函数,后面可以是1个或多个列表,后面的列表会把每一项作为参数传递给前面的函数,返回的是一个迭代对象。
def square(x):
return x ** 2
list = map(square, [1, 2, 3, 4, 5]) # 计算列表各个元素的平方
print(type(list))
print(list)
输出:<class 'map'>
<map object at 0x104d0d940>
- map结合lambda表达式使用
list = list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))
print(list)
输出:[1, 4, 9, 16, 25]
- 传入多个列表
list = list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
print(list)
输出:[3, 7, 11, 15, 19]