python map and reduce, give me an example
时间: 2024-05-01 22:19:37 浏览: 91
Python map和reduce函数用法示例
5星 · 资源好评率100%
Sure! Here's an example of using map and reduce in Python:
Let's say we want to add together a list of numbers. We can first use map to convert each number from a string to an integer, and then use reduce to add them all together.
```
from functools import reduce
numbers = ['1', '2', '3', '4', '5']
numbers_int = map(int, numbers)
sum_of_numbers = reduce(lambda x, y: x + y, numbers_int)
print(sum_of_numbers)
```
Output:
```
15
```
In this example, we first convert each element of the `numbers` list to an integer using `map(int, numbers)`. This creates a new list where each element is an integer.
Then, we use `reduce` to add all the elements of the `numbers_int` list together. The `lambda` function passed to reduce takes two arguments (x and y) and returns their sum. `reduce` applies this function to each element of the list, iteratively combining them until the final result is obtained.
阅读全文