Python 内置函数

Python map() 函数用于把一个函数批量应用到可迭代对象的每个元素。

语法

map(function, iterable)

参数

function:应用到每个元素的函数。第二个参数 iterable:可迭代对象(可多个,函数接收对应个数的参数)。

返回值

返回 map 对象(迭代器),逐个产出函数处理后的结果。要列表用 list()

示例

def square(x):
    return x * x

nums = [1, 2, 3, 4]
print(list(map(square, nums)))        # [1, 4, 9, 16]

# 用 lambda 更简洁
print(list(map(lambda x: x * 2, nums)))  # [2, 4, 6, 8]

# 字符串转数字
strs = ["1", "2", "3"]
print(list(map(int, strs)))           # [1, 2, 3]

# 多个可迭代对象
a = [1, 2, 3]
b = [10, 20, 30]
print(list(map(lambda x, y: x + y, a, b)))  # [11, 22, 33]

输出:

[1, 4, 9, 16]
[2, 4, 6, 8]
[1, 2, 3]
[11, 22, 33]

注意事项

map 返回迭代器,要列表用 list()。简单变换用列表推导式更直观:[x * x for x in nums]