在Python中,`map()`函数是一个内置的高阶函数,用于将一个函数应用于一个序列的所有元素,并返回一个迭代器。以下是`map()`函数的基本用法:
```python
map(function, iterable, ...)
`function`:一个函数,可以是内置的,也可以是自定义的,甚至可以是匿名函数(lambda函数)。
`iterable`:一个或多个可迭代对象,如列表、元组、字符串等。
`map()`函数将`function`依次作用于`iterable`的每个元素,并返回一个迭代器。如果需要将结果转换为列表,可以使用`list()`函数。
示例
类型转换
```python
str_numbers = ['1', '2', '3']
int_numbers = list(map(int, str_numbers))
print(int_numbers) 输出: [1, 2, 3]
数据格式化
```python
float_numbers = [3.14159, 2.71828, 1.61803]
formatted_numbers = list(map(lambda x: f'{x:.2f}', float_numbers))
print(formatted_numbers) 输出: ['3.14', '2.72', '1.62']
并行迭代
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sum_list = list(map(lambda x, y: x + y, list1, list2))
print(sum_list) 输出: [5, 7, 9]
复杂函数应用
```python
def format_name(s):
return s.upper() + s[1:].lower()
names = ['adam', 'LISA', 'barT']
formatted_names = list(map(format_name, names))
print(formatted_names) 输出: ['Adam', 'Lisa', 'Bart']
使用lambda匿名函数
```python
squares = map(lambda x: x2, [1, 2, 3, 4, 5])
for num in squares:
print(num) 输出: 1, 4, 9, 16, 25
多个可迭代对象
```python
ls1 = ' ABC '
ls2 = ' abc '
print(list(map(lambda x, y: x + y, ls1, ls2))) 输出: ['Aa', 'Bb', 'Cc']
处理长度不同的可迭代对象
```python
ls1 = ' ABC '
ls2 = ' ab '
print(list(map(lambda x, y: x + y, ls1, ls2))) 输出: ['Aa', 'Bb', 'Cc']
注意,在Python 3中,如果传入的多个可迭代对象长度不相同,`map()`会按照最短的长度进行处理。
希望这些示例能帮助你理解`map()`函数在Python中的用法