python内置函数之map()

1、map() 函数的简介和语法

 

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

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

语法

map() 函数语法:map(function, iterable, …)

参数

function – 函数
iterable – 一个或多个序列

返回值

Python 3.x 返回迭代器。python 2.x 直接返回列表。
 
 

2、map()用法实例

def square(x) :            
    return x ** 2
map(square, [1,2,3,4,5])

输出结果:<map at 0x1acd1c94be0>
 
python3可将map转换为list:
def square(x) :            # 计算平方数
    return x ** 2
A=list(map(square, [1,2,3,4,5]))   # 计算列表各个元素的平方
print(A)

输出结果:
[1, 4, 9, 16, 25]
result1 = map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
# 获取对象中的元素
print(list(result))
# 提供了两个列表,对相同位置的列表数据进行相加
result2 = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
print(list(result2))


输出结果:
[1, 4, 9, 16, 25]
[3, 7, 11, 15, 19]

原文地址:https://www.cnblogs.com/hq1015/p/15061868.html