Python 匿名函数、map、filter、sort 用法详解
1、匿名函数
匿名函数lambda:临时使用的小函数,不用起名字
基本语法:
lambda 参数: 表达式
示例:
# 普通函数
def add(x, y):return x + y# 等价匿名函数
add_lambda = lambda x, y: x + yprint(add(3, 5)) # 8
print(add_lambda(3, 5)) # 8
常见用法:
# 1. 简单的数学运算
square = lambda x: x ** 2
print(square(5)) # 25# 2. 字符串处理
get_first_char = lambda s: s[0]
print(get_first_char("Hello")) # H# 3. 条件判断
is_even = lambda x: "偶数" if x % 2 == 0 else "奇数"
print(is_even(4)) # 偶数
print(is_even(7)) # 奇数# 4. 多个参数
multiply = lambda a, b, c: a * b * c
print(multiply(2, 3, 4)) # 24
2、map函数
把列表中的每个元素都加工、处理一遍
基本语法
map(函数, 列表)
'''
map的用法
'''
numbers = [1,2,3,4,5]
squared = []
for num in numbers:squared.append(num ** 2)
print(squared) # [1, 4, 9, 16, 25]# 使用 map + 普通函数
def square(x):return x ** 2numbers = [1, 2, 3, 4, 5]
squared = list(map(square, numbers))
print(squared) # [1, 4, 9, 16, 25]# 使用 map + 匿名函数(更简洁)
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
map案例
'''
更多map示例
'''
# 字符串列表中每个元素首字母大写
names = ['aa','bb','cc']
result = list(map(lambda name:name.capitalize(),names))
print(result)
# 2、多个列表同时处理
a = [100,200,300]
b = [0.1,0.2,0.3]
result = list(map(lambda one,two : one*(1-two),a,b))
print(result)
#类型转换
a = ['1','2','3']
result = list(map(int,a))
print(result)
# 字典格式处理
students = [{"name": "Alice", "age": 20}, {"name": "Bob", "age": 22}]
result = list(map(lambda stu:stu['name'],students))
print(result)
3、filter函数
从列表中筛选出满足条件的元素
语法:
filter(判断函数, 列表)
示例:
# 传统方法:用 for 循环
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in numbers:if num % 2 == 0:even_numbers.append(num)
print(even_numbers) # [2, 4, 6, 8, 10]# 使用 filter + 普通函数
def is_even(x):return x % 2 == 0numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(is_even, numbers))
print(even_numbers) # [2, 4, 6, 8, 10]# 使用 filter + 匿名函数
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6, 8, 10]
filter示例分析
# 1. 筛选字符串
words = ["apple", "banana", "cat", "dog", "elephant"]
long_words = list(filter(lambda word: len(word) > 4, words))
print(long_words) # ['apple', 'banana', 'elephant']# 2. 筛选非空值
data = ["", "hello", None, "world", "", "python"]
non_empty = list(filter(None, data)) # None 会自动过滤掉假值
print(non_empty) # ['hello', 'world', 'python']# 3. 筛选数字范围
numbers = [15, 8, 22, 35, 9, 18, 7]
between_10_20 = list(filter(lambda x: 10 <= x <= 20, numbers))
print(between_10_20) # [15, 18]# 4. 筛选字典列表
students = [{"name": "Alice", "score": 85},{"name": "Bob", "score": 92},{"name": "Charlie", "score": 78},{"name": "David", "score": 65}
]
good_students = list(filter(lambda s: s["score"] >= 80, students))
print(good_students) # [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}]
4、sorted函数
给列表排队,可以按照各种规则排序
基本语法
sorted(列表, key=排序规则, reverse=是否倒序)
示例:
# 1. 基本排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 1, 2, 3, 4, 5, 6, 9]# 倒序排序
reverse_sorted = sorted(numbers, reverse=True)
print(reverse_sorted) # [9, 6, 5, 4, 3, 2, 1, 1]# 2. 字符串排序
fruits = ["banana", "apple", "cherry", "date"]
sorted_fruits = sorted(fruits)
print(sorted_fruits) # ['apple', 'banana', 'cherry', 'date']
使用key参数自定义排序规则
'''
sorted函数用法,自定义规则
'''
# 1. 按字符串长度排序
words = ["cat", "elephant", "dog", "butterfly"]
sorted_by_length = sorted(words, key=lambda x: len(x))
print(sorted_by_length) # ['cat', 'dog', 'elephant', 'butterfly']
# 2、对字典排序
students = [{"name": "Alice", "age": 20},{"name": "Bob", "age": 18},{"name": "Charlie", "age": 22}
]
# 按年龄排序
sorted_by_age = sorted(students, key=lambda s: s["age"])
print(sorted_by_age) # [{'name': 'Bob', 'age': 18}, {'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 22}]
# 按姓名排序
sorted_by_name = sorted(students, key=lambda s: s["name"])
print(sorted_by_name) # [{'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 18}, {'name': 'Charlie', 'age': 22}]
# 多重排序条件
# 先按分数降序,再按姓名升序
students = [{"name": "Alice", "score": 85},{"name": "Bob", "score": 85},{"name": "Charlie", "score": 90}
]
# 你可以理解为默认为升序,负号-表示取反的意思
sorted_students = sorted(students, key=lambda s: (-s["score"], s["name"]))
print(sorted_students)
# [{'name': 'Charlie', 'score': 90}, {'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 85}]
5、综合案例
学生成绩处理
# 场景1:学生成绩处理
def process_student_grades():print("\n=== 学生成绩处理 ===")students = [{"name": "张三", "math": 85, "english": 78, "science": 92},{"name": "李四", "math": 72, "english": 88, "science": 65},{"name": "王五", "math": 90, "english": 85, "science": 78},{"name": "赵六", "math": 68, "english": 72, "science": 81}]# 计算每个学生的平均分students_with_avg = list(map(lambda s: {**s, "average": round((s["math"] + s["english"] + s["science"]) / 3, 2)},students))print("学生成绩(含平均分):")for student in students_with_avg:print(f"{student['name']}: 平均分 {student['average']}")# 筛选平均分80分以上的学生top_students = list(filter(lambda s: s["average"] >= 80, students_with_avg))print("\n优秀学生(平均分≥80):")for student in top_students:print(f"{student['name']}: {student['average']}")# 按平均分降序排列ranked_students = sorted(students_with_avg, key=lambda s: s["average"], reverse=True)print("\n学生排名:")for i, student in enumerate(ranked_students, 1):print(f"第{i}名: {student['name']} - {student['average']}")process_student_grades()# 场景2:文本处理
def text_processing():print("\n=== 文本处理 ===")sentences = ["Python is a powerful programming language","I love learning new things","Functional programming is interesting","Map filter and sorted are useful functions"]# 找出包含 'python' 或 'programming' 的句子(不区分大小写)programming_sentences = list(filter(lambda s: any(word in s.lower() for word in ['python', 'programming']),sentences))print("包含编程相关词汇的句子:")for sentence in programming_sentences:print(f"- {sentence}")# 按句子长度排序sorted_by_length = sorted(sentences, key=lambda s: len(s))print("\n按长度排序的句子:")for sentence in sorted_by_length:print(f"- {sentence} (长度: {len(sentence)})")text_processing()
6、总结
-
lambda:匿名小函数
-
map:每个都处理
-
filter:只留符合条件的
-
sorted:重新排队