Python函数式编程掌握lambda、map与filter的高效技巧
```python
# lambda函数的基本应用
square = lambda x: x2
result = square(5)
print(flambda平方计算: {result})
# 匿名函数的即时调用
result = (lambda x, y: x + y)(3, 4)
print(flambda即时调用: {result})
# map函数的应用
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x2, numbers))
print(fmap平方转换: {squared_numbers})
# 多序列映射
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sum_list = list(map(lambda x, y: x + y, list1, list2))
print(f多序列映射求和: {sum_list})
# filter函数的应用
numbers = range(10)
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(ffilter筛选偶数: {even_numbers})
# 复杂条件过滤
words = [apple, banana, cherry, date, elderberry]
long_words = list(filter(lambda word: len(word) > 5, words))
print(ffilter筛选长单词: {long_words})
# 组合使用map和filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(map(lambda x: x2, filter(lambda x: x % 2 == 0, numbers)))
print(f组合使用: {result})
# 处理字典数据
students = [
{name: Alice, score: 85},
{name: Bob, score: 92},
{name: Charlie, score: 78}
]
# 提取姓名列表
names = list(map(lambda student: student[name], students))
print(f提取姓名: {names})
# 筛选高分学生
high_scores = list(filter(lambda student: student[score] > 80, students))
print(f高分学生: {high_scores})
# 字符串处理应用
texts = [ hello , WORLD , python ]
cleaned_texts = list(map(lambda text: text.strip().lower(), texts))
print(f字符串处理: {cleaned_texts})
# 嵌套lambda函数
multiplier = lambda x: (lambda y: x y)
double = multiplier(2)
triple = multiplier(3)
print(f嵌套lambda - 双倍: {double(5)})
print(f嵌套lambda - 三倍: {triple(5)})
# 条件lambda函数
categorize = lambda x: 正数 if x > 0 else (零 if x == 0 else 负数)
print(f条件lambda: {categorize(5)}, {categorize(-3)}, {categorize(0)})
# 实际应用:数据清洗
data = [25.5, 30, invalid, 42.3, NaN]
cleaned_data = list(map(float, filter(lambda x: x.replace('.', '').isdigit(), data)))
print(f数据清洗结果: {cleaned_data})
# 性能比较:传统循环 vs 函数式编程
import time
numbers = list(range(1000000))
# 传统循环方式
start_time = time.time()
squared_loop = []
for num in numbers:
squared_loop.append(num2)
loop_time = time.time() - start_time
# 函数式编程方式
start_time = time.time()
squared_func = list(map(lambda x: x2, numbers))
func_time = time.time() - start_time
print(f传统循环耗时: {loop_time:.4f}秒)
print(f函数式编程耗时: {func_time:.4f}秒)
# 高级技巧:链式操作
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 链式处理:筛选 -> 转换 -> 聚合
result = reduce(
lambda x, y: x + y,
map(
lambda x: x2,
filter(lambda x: x % 2 == 0, numbers)
)
)
print(f链式操作结果: {result})
# 实际案例:文本分析
sentences = [
Python is a great programming language,
Functional programming is powerful,
Lambda functions are anonymous
]
# 统计包含特定关键词的句子
keywords = [Python, functional, lambda]
filtered_sentences = list(filter(
lambda sentence: any(keyword.lower() in sentence.lower() for keyword in keywords),
sentences
))
print(f关键词过滤结果: {filtered_sentences})
# 列表推导式与函数式编程对比
numbers = [1, 2, 3, 4, 5]
# 列表推导式
squares_lc = [x2 for x in numbers if x % 2 == 0]
# 函数式编程
squares_fp = list(map(lambda x: x2, filter(lambda x: x % 2 == 0, numbers)))
print(f列表推导式: {squares_lc})
print(f函数式编程: {squares_fp})
# 错误处理技巧
def safe_operation(func, default=None):
def wrapper(args, kwargs):
try:
return func(args, kwargs)
except Exception:
return default
return wrapper
# 安全的数据转换
unsafe_data = [123, 456, abc, 789]
safe_convert = safe_operation(lambda x: int(x), default=0)
converted_data = list(map(safe_convert, unsafe_data))
print(f安全数据转换: {converted_data})
```
更多推荐
所有评论(0)