在 Python 中,map() 函数是一个用于对可迭代对象中的每个元素应用指定函数的内置函数,返回一个包含函数计算结果的新迭代器。它是 Python 中常见的函数式编程工具之一,能提高代码的简洁性和可读性[^3]。
### 基本语法
```python
map(function, iterable)
```
- `function`:要应用的函数。
- `iterable`:一个或多个可迭代对象(如列表、元组、字符串等)[^3]。
### 基本用法示例
#### 示例 1:将列表中的每个元素乘以 2
```python
def multiply_by_two(x):
return x * 2
numbers = [1, 2, 3, 4]
result = map(multiply_by_two, numbers)
print(list(result)) # 输出: [2, 4, 6, 8]
```
#### 示例 2:计算列表中所有元素的绝对值
```python
numbers = [-1, -2, 3, -4]
result = map(abs, numbers)
print(list(result)) # 输出: [1, 2, 3, 4]
```
### 与 lambda 表达式结合使用
#### 示例 3:将字符串列表中的每个元素转换为大写
```python
words = ['hello', 'world']
result = map(lambda x: x.upper(), words)
print(list(result)) # 输出: ['HELLO', 'WORLD']
```
#### 示例 4:将字符串中的每个字符转换为大写
```python
string = 'hello'
result = map(lambda x: x.upper(), string)
print(list(result)) # 输出: ['H', 'E', 'L', 'L', 'O']
```
### 处理多个可迭代对象
#### 示例 5:将两个列表中的元素相加
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = map(lambda x, y: x + y, list1, list2)
print(list(result)) # 输出: [5, 7, 9]
```
#### 示例 6:将三个列表中的元素相加
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
result = map(lambda x, y, z: x + y + z, list1, list2, list3)
print(list(result)) # 输出: [12, 15, 18]
```
### 异常处理与 map()
#### 示例 7:使用 `map()` 和 `try-except` 处理可能的异常
```python
def safe_sqrt(x):
try:
return x ** 0.5
except ValueError:
return None
numbers = [-1, 4, 9]
result = map(safe_sqrt, numbers)
print(list(result)) # 输出: [None, 2.0, 3.0]
```
### 与其他内置函数的结合
#### 示例 8:结合使用 `map()` 和 `filter()`
```python
numbers = [1, 2, 3, 4, 5, 6]
even_squares = map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers))
print(list(even_squares)) # 输出: [4, 16, 36]
```