map()
是 Python 的一个内置高阶函数,用于对可迭代对象(如列表、元组等)中的每个元素应用指定的函数,并返回一个迭代器(iterator)。它常用于批量处理数据,避免显式编写循环。
map(function, iterable, ...)
function
**:要应用的函数(可以是 lambda
或普通函数)。iterable
**:可迭代对象(如 list
、tuple
、str
等)。map
对象(迭代器),可以使用 list()
、tuple()
等转换为具体的数据结构。numbers = [1, 2, 3, 4]
squared = map(lambda x: x ** 2, numbers)
print(list(squared)) # 输出: [1, 4, 9, 16]
def double(x):
return x * 2
numbers = [1, 2, 3]
doubled = map(double, numbers)
print(list(doubled)) # 输出: [2, 4, 6]
map()
可以接受多个可迭代对象,函数需要对应数量的参数:
a = [1, 2, 3]
b = [4, 5, 6]
sums = map(lambda x, y: x + y, a, b)
print(list(sums)) # 输出: [5, 7, 9]
map()
的特点map()
返回的是迭代器,不会立即计算所有结果,只有在需要时(如 list()
、for
循环)才会逐个生成值:
numbers = [1, 2, 3]
mapped = map(lambda x: x * 2, numbers) # 此时并未计算
print(mapped) # 输出:
由于 map()
是惰性的,它适合处理大型数据集,避免一次性占用过多内存:
# 假设有一个非常大的列表
big_data = range(1_000_000) # 100 万个数字
mapped = map(lambda x: x * 2, big_data) # 不会立即计算
# 可以逐批处理
for chunk in mapped:
process(chunk) # 避免内存爆炸
map()
vs 列表推导式特性 | map() |
列表推导式(List Comprehension) |
---|---|---|
语法 | map(func, iterable) |
[func(x) for x in iterable] |
返回值 | 迭代器(map 对象) |
直接生成列表 |
性能 | 通常稍快(惰性计算) | 稍慢(立即计算) |
可读性 | 适合简单函数(如 lambda ) |
适合复杂逻辑 |
适用场景 | 函数式编程、大数据处理 | 日常 Python 代码 |
# 使用 map()
numbers = [1, 2, 3]
result = map(lambda x: x * 2, numbers)
# 使用列表推导式
result = [x * 2 for x in numbers]
names = [" alice ", "BOB", " charlie "]
cleaned = map(lambda x: x.strip().title(), names)
print(list(cleaned)) # 输出: ['Alice', 'Bob', 'Charlie']
str_numbers = ["1", "2", "3"]
int_numbers = map(int, str_numbers)
print(list(int_numbers)) # 输出: [1, 2, 3]
prices = [10, 20, 30]
quantities = [2, 3, 1]
totals = map(lambda p, q: p * q, prices, quantities)
print(list(totals)) # 输出: [20, 60, 30]
**map()
返回的是迭代器**,如果多次遍历,需要先转换为 list
或 tuple
:
mapped = map(lambda x: x * 2, [1, 2, 3])
print(list(mapped)) # 第一次遍历: [2, 4, 6]
print(list(mapped)) # 第二次遍历: [](迭代器已耗尽)
如果函数较复杂,建议用 def
定义,避免 lambda
降低可读性:
# 不推荐(可读性差)
mapped = map(lambda x: x ** 2 if x % 2 == 0 else x * 3, numbers)
# 推荐(更清晰)
def transform(x):
return x ** 2 if x % 2 == 0 else x * 3
mapped = map(transform, numbers)
**map()
不会修改原数据**,而是返回新结果:
numbers = [1, 2, 3]
squared = map(lambda x: x ** 2, numbers)
print(numbers) # 原列表不变: [1, 2, 3]
map(function, iterable)
用于对可迭代对象的每个元素应用函数。def
或列表推导式。lambda
、filter()
、reduce()
进行函数式编程。filter()
**:筛选符合条件的元素 evens = filter(lambda x: x % 2 == 0, [1, 2, 3, 4])
reduce()
**(需 from functools import reduce
):累积计算 from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4]) # 1 * 2 * 3 * 4=24
希望这份指南能帮助你掌握 map()
!