Python map()函数
map()函数在将给定函数应用于给定可迭代对象(列表、元组等)的每个项目后返回结果的映射对象(它是一个迭代器)
句法 :
map(fun, iter)
参数 :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
注意:您可以将一个或多个可迭代对象传递给 map()函数。
返回:
Returns a list of the results after applying the given function
to each item of a given iterable (list, tuple etc.)
注意: map() (地图对象)的返回值可以传递给 list() (创建列表)、 set() (创建集合)等函数。代码 1
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
输出 :
[2, 4, 6, 8]
代码 2
我们还可以使用带有 map 的 lambda 表达式来实现上述结果。
# Double all numbers using map and lambda
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
输出 :
[2, 4, 6, 8]
代码 3
# Add two lists using map and lambda
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result))
输出 :
[5, 7, 9]
代码 4
# List of strings
l = ['sat', 'bat', 'cat', 'mat']
# map() can listify the list of strings individually
test = list(map(list, l))
print(test)
输出 :
[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]