Python函数式编程利用lambda、map和filter提升代码简洁性
```python
# 函数式编程利器:lambda、map和filter提升代码简洁性
# lambda表达式:创建匿名函数
square = lambda x: x 2
is_even = lambda x: x % 2 == 0
# 传统方式 vs lambda方式
def square_def(x):
return x 2
numbers = [1, 2, 3, 4, 5]
# 使用map进行数据转换
squared_numbers = list(map(lambda x: x 2, numbers))
# 等价于:[x2 for x in numbers]
# 使用filter进行数据筛选
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# 等价于:[x for x in numbers if x % 2 == 0]
# 组合使用map和filter
squared_evens = list(map(lambda x: x 2,
filter(lambda x: x % 2 == 0, numbers)))
# 处理字符串数据
words = ['hello', 'world', 'python', 'functional']
capitalized_words = list(map(lambda word: word.upper(), words))
# 复杂数据处理
data = [{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30},
{'name': 'Charlie', 'age': 35}]
# 提取年龄大于28的人名
names_over_28 = list(map(lambda person: person['name'],
filter(lambda person: person['age'] > 28, data)))
# 数学运算示例
import math
points = [(1, 2), (3, 4), (5, 6)]
distances = list(map(lambda point: math.sqrt(point[0]2 + point[1]2), points))
# 多参数lambda与map
add_numbers = lambda x, y: x + y
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sums = list(map(add_numbers, list1, list2))
# 条件过滤的复杂示例
mixed_data = [1, 'hello', 3.14, 42, 'world', 2.71]
integers_only = list(filter(lambda x: isinstance(x, int), mixed_data))
# 性能优化:使用生成器表达式
large_numbers = range(1000000)
even_squares_gen = map(lambda x: x 2,
filter(lambda x: x % 2 == 0, large_numbers))
# 实际应用:数据清洗
raw_data = [' hello ', ' WORLD ', ' PYTHON ']
cleaned_data = list(map(lambda s: s.strip().lower(), raw_data))
# 函数组合
def compose(f, g):
return lambda x: f(g(x))
to_upper = lambda s: s.upper()
add_exclamation = lambda s: s + '!'
shout = compose(to_upper, add_exclamation)
# 使用示例
result = list(map(shout, ['hello', 'world']))
```
更多推荐
所有评论(0)