如何使用Python中的`sorted()`函数
Python中的sorted()函数是一个内置函数,用于对序列进行排序。它的语法如下:
sorted(iterable, key=None, reverse=False)
其中iterable是要排序的序列(例如列表、元组、集合等),key是一个函数用于指定排序时的比较方式(默认为None),reverse是一个布尔值,用于指定排序顺序(默认为升序)。
下面我们将详细讨论sorted()函数的使用,包括基本使用方法、自定义比较函数以及如何处理复杂类型的排序。
### 基本用法
最基本的排序方法是对列表进行升序排列,例如:
>>> lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] >>> sorted_lst = sorted(lst) >>> print(sorted_lst) [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
sorted()函数将lst进行升序排列,返回一个新的有序列表sorted_lst。如果我们想要对列表进行降序排列,可以设置reverse=True:
>>> sorted_lst = sorted(lst, reverse=True) >>> print(sorted_lst) [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
sorted()函数还可以用于对元组和集合进行排序,例如:
>>> tpl = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
>>> sorted_tpl = sorted(tpl)
>>> print(sorted_tpl)
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
>>> st = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
>>> sorted_st = sorted(st)
>>> print(sorted_st)
[1, 2, 3, 4, 5, 6, 9]
### 自定义比较函数
sorted()函数还可以使用自定义的比较函数来指定排序方式。比较函数接受一个参数,并返回一个用于排序的键值。例如,如果要对字符串进行排序,可以按照字符串长度进行排序:
>>> lst = ['apple', 'banana', 'cat', 'dog'] >>> sorted_lst = sorted(lst, key=len) >>> print(sorted_lst) ['cat', 'dog', 'apple', 'banana']
这里通过key参数指定了比较函数len。sorted()函数将lst中的元素作为参数传递给len函数,根据返回的键值进行排序。
自定义比较函数也可以实现更加复杂的排序方式。例如,如果要对学生列表按照成绩进行排序,可以定义一个返回成绩的函数:
def get_score(student):
return student['score']
students = [
{'name': 'Alice', 'score': 80},
{'name': 'Bob', 'score': 70},
{'name': 'Charlie', 'score': 90},
{'name': 'David', 'score': 85}
]
sorted_students = sorted(students, key=get_score)
print(sorted_students)
输出结果为:
[{'name': 'Bob', 'score': 70},
{'name': 'Alice', 'score': 80},
{'name': 'David', 'score': 85},
{'name': 'Charlie', 'score': 90}]
### 处理复杂类型的排序
sorted()函数可以处理包含不同类型数据的嵌套序列(例如列表中包含元组),只要在比较函数中返回可比较的键值即可。例如,如果要对包含学生信息的列表进行排序,可以定义一个返回元组作为键值的函数:
def get_student_key(student):
score = student['score']
name = student['name']
return (score, name)
students = [
{'name': 'Alice', 'score': 80},
{'name': 'Charlie', 'score': 90},
{'name': 'David', 'score': 85},
{'name': 'Bob', 'score': 70}
]
sorted_students = sorted(students, key=get_student_key)
print(sorted_students)
输出结果为:
[{'name': 'Bob', 'score': 70},
{'name': 'Alice', 'score': 80},
{'name': 'David', 'score': 85},
{'name': 'Charlie', 'score': 90}]
这里定义了一个返回(score, name)元组的函数get_student_key,根据元组进行排序。
对于复杂类型的列表,可以通过指定多个排序规则来进行排序。例如,如果要对包含学生信息和班级信息的列表按照成绩和班级号进行排序,可以定义一个返回元组作为键值的函数:
def get_student_key(student):
score = student['score']
name = student['name']
cls = student['class']
return (score, cls, name)
students = [
{'name': 'Alice', 'score': 80, 'class': 'A'},
{'name': 'Charlie', 'score': 90, 'class': 'B'},
{'name': 'David', 'score': 85, 'class': 'B'},
{'name': 'Bob', 'score': 70, 'class': 'A'}
]
sorted_students = sorted(students, key=get_student_key)
print(sorted_students)
输出结果为:
[{'name': 'Bob', 'score': 70, 'class': 'A'},
{'name': 'Alice', 'score': 80, 'class': 'A'},
{'name': 'David', 'score': 85, 'class': 'B'},
{'name': 'Charlie', 'score': 90, 'class': 'B'}]
这里定义了一个返回(score, cls, name)元组的函数get_student_key,以成绩、班级号和姓名的顺序进行排序。
