在Python中,`map()`函数是一个内置函数,用于将一个函数应用于一个序列中的每个元素,并返回一个新的列表。以下是`map()`函数的基本用法:
基本语法
```python
map(function, iterable, ...)
`function`:一个函数,该函数将应用于`iterable`中的每个元素。
`iterable`:一个或多个可迭代对象(如列表、元组、字符串等)。
`...`:表示可以传递多个`iterable`参数。
示例
使用内置函数 `str()`
```python
a = list(map(str, 'python'))
print(a) 输出:['p', 'y', 't', 'h', 'o', 'n']
使用自定义函数 `add()`
```python
def add(x, y):
return x + y
list1 = [1, 2, 3]
list2 = [4, 5, 6]
a = list(map(add, list1, list2))
print(a) 输出:[5, 7, 9]
使用 `lambda` 匿名函数
```python
a = list(map(lambda x: x2, range(11)))
print(a) 输出:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
使用多个 `iterable` 参数
```python
a, b, c = map(int, [1.7, 6.8, 4.5])
print("a={}, b={}, c={}".format(a, b, c)) 输出:a=1, b=6, c=4
将 `map` 对象转换为列表
```python
b = map(add, [1, 2, 3])
print(list(b)) 输出:[2, 4, 6]
使用 `map` 函数进行类型转换
```python
a = map(int, (1, 2, 3))
print(list(a)) 输出:[1, 2, 3]
`map()`函数返回的是一个迭代器,如果需要立即查看结果,可以使用`list()`函数将其转换为列表。需要注意的是,`map()`函数不会改变原有的序列,而是返回一个新的序列