python map函数
时间: 2023-12-09 16:54:35 浏览: 18
map()函数是Python内置的高阶函数,它接收两个参数,第一个参数是一个函数,第二个参数是一个序列(可以是列表、元组等)。map()函数将第一个参数(函数)依次作用于序列中的每个元素,将结果作为新序列返回。
例如,下面的代码使用map()函数将一个列表中的每个元素都平方:
```python
lst = [1, 2, 3, 4, 5]
squared_lst = list(map(lambda x: x**2, lst))
print(squared_lst) # 输出 [1, 4, 9, 16, 25]
```
这里使用了lambda表达式定义了一个函数,它将输入的参数平方,并将其作为map()函数的第一个参数。map()函数将这个函数依次作用于lst中的每个元素,生成一个新的序列squared_lst。最后使用list()函数将其转换为列表输出。
map()函数还可以接收多个序列作为参数,此时它的第一个参数应该是一个函数,这个函数的参数个数应该与序列的个数相同。例如:
```python
lst1 = [1, 2, 3, 4, 5]
lst2 = [10, 20, 30, 40, 50]
result_lst = list(map(lambda x, y: x + y, lst1, lst2))
print(result_lst) # 输出 [11, 22, 33, 44, 55]
```
这里定义了一个函数,它接收两个参数并将它们相加。map()函数将这个函数依次作用于lst1和lst2中的每个元素,生成一个新的序列result_lst,最后使用list()函数将其转换为列表输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)