Python map()函数
时间:2020-03-05 15:31:29 来源:igfitidea点击:
map()是Python中的一个内置函数,它将函数应用于给定iterable中的所有元素。
它允许您在不使用循环的情况下编写简单而干净的代码。
Python map()函数
函数的形式如下:
map(function, iterable, ...)
它接受两个强制参数:
函数-为iterable的每个元素调用的函数。
iterable—一个或者多个支持迭代的对象。
Python中的大多数内置对象,如列表、字典和元组都是iterable。
在Python3中,map()返回一个大小等于传递的iterable对象的map对象。
在python2中,函数返回一个列表。
让我们看一个例子来更好地解释map()函数是如何工作的。
假设我们有一个字符串列表,我们希望将列表中的每个元素转换为大写。
一种方法是使用传统的for循环:
directions = ["north", "east", "south", "west"] directions_upper = [] for direction in directions: d = direction.upper() directions_upper.append(d) print(directions_upper)
['NORTH', 'EAST', 'SOUTH', 'WEST']
使用map()函数,代码将更加简单和灵活。
def to_upper_case(s): return s.upper() directions = ["north", "east", "south", "west"] directions_upper = map(to_upper_case, directions) print(list(directions_upper))
我们使用list()构造函数将返回的映射对象转换为列表:
['NORTH', 'EAST', 'SOUTH', 'WEST']
如果回调函数很简单,则更具python风格的方法是使用lambda函数:
directions = ["north", "east", "south", "west"] directions_upper = map(lambda s: s.upper(), directions) print(list(directions_upper))
A lambda function is a small anonymous function.
下面是另一个示例,演示如何创建从1到10的平方数列表:
squares = map(lambda n: n*n , range(1, 11)) print(list(squares))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
将map()与多个iterable一起使用
您可以向map()函数传递任意数量的ITerable。
回调函数接受的必需输入参数的数目必须与ITerable的数目相同。
以下示例演示如何对两个列表执行元素级乘法:
def multiply(x, y): return x * y a = [1, 4, 6] b = [2, 3, 5] result = map(multiply, a, b) print(list(result))
[2, 12, 30]
相同的代码,但使用lambda函数将如下所示:
a = [1, 4, 6] b = [2, 3, 5] result = map(lambda x, y: x*y, a, b) print(list(result))
当提供多个iterable时,返回对象的大小等于最短的iterable。
让我们看一个Iterable长度不相同的示例:
a = [1, 4, 6] b = [2, 3, 5, 7, 8] result = map(lambda x, y: x*y, a, b) print(list(result))
忽略多余元素(7和8):
[2, 12, 30]