给出五个函数式编程的python程序源码
时间: 2024-04-29 12:26:41 浏览: 56
当然,很乐意为您提供五个函数式编程的Python程序源码,如下所示:
1. Map 函数示例:
```
list_numbers = [1, 2, 3, 4, 5]
def square(x):
return x ** 2
squared_numbers = list(map(square, list_numbers))
print(squared_numbers)
```
输出: `[1, 4, 9, 16, 25]`
2. Filter 函数示例:
```
list_numbers = [1, 2, 3, 4, 5]
def is_even(x):
return x % 2 == 0
even_numbers = list(filter(is_even, list_numbers))
print(even_numbers)
```
输出: `[2, 4]`
3. Reduce 函数示例:
```
from functools import reduce
list_numbers = [1, 2, 3, 4, 5]
def multiply(x, y):
return x * y
product = reduce(multiply, list_numbers)
print(product)
```
输出: `120`
4. Lambda 函数示例:
```
list_numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, list_numbers))
print(squared_numbers)
```
输出: `[1, 4, 9, 16, 25]`
5. List Comprehension 示例:
```
list_numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in list_numbers]
print(squared_numbers)
```
输出: `[1, 4, 9, 16, 25]`
阅读全文