欢迎访问宙启技术站
智能推送

如何使用sorted()函数来对Python列表进行排序?

发布时间:2023-06-29 16:14:14

sorted()函数是Python内置的用于在列表上进行排序的函数。它可以接受一个可迭代对象作为输入,并返回一个对原始输入进行排序的新列表。sorted()函数可以用于数字、字符串、元组、字典、集合等各种类型的数据。

以下是如何使用sorted()函数对Python列表进行排序的示例:

1. 对一个数字列表进行排序:

numbers = [4, 2, 7, 1, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出:[1, 2, 4, 5, 7]

上述代码创建了一个数字列表numbers,并使用sorted()函数对其进行排序。sorted_numbers将保存排序后的列表。

2. 对一个字符串列表进行排序:

fruits = ['apple', 'banana', 'cherry', 'date']
sorted_fruits = sorted(fruits)
print(sorted_fruits)  # 输出:['apple', 'banana', 'cherry', 'date']

上述代码创建了一个字符串列表fruits,并使用sorted()函数对其进行排序。sorted_fruits将保存排序后的列表。

3. 对一个元组列表进行排序:

people = [('John', 25), ('Peter', 35), ('Mary', 30)]
sorted_people = sorted(people, key=lambda x: x[1])
print(sorted_people)  # 输出:[('John', 25), ('Mary', 30), ('Peter', 35)]

上述代码创建了一个元组列表people,其中每个元组包含一个人的名字和年龄。使用sorted()函数对这个列表进行排序,可以通过指定关键字参数key来指定按照哪个字段进行排序。上述示例使用lambda函数作为key来指定按照年龄字段进行排序。

4. 对一个字典列表进行排序:

students = [{'name': 'John', 'age': 25}, {'name': 'Mary', 'age': 30}, {'name': 'Peter', 'age': 35}]
sorted_students = sorted(students, key=lambda x: x['age'])
print(sorted_students)  # 输出:[{'name': 'John', 'age': 25}, {'name': 'Mary', 'age': 30}, {'name': 'Peter', 'age': 35}]

上述代码创建了一个字典列表students,其中每个字典表示一个学生,包含名字和年龄。使用sorted()函数对这个列表进行排序,可以通过指定关键字参数key来指定按照哪个字段进行排序。上述示例使用lambda函数作为key来指定按照年龄字段进行排序。

5. 对一个集合进行排序:

colors = {'red', 'blue', 'green', 'yellow'}
sorted_colors = sorted(colors)
print(sorted_colors)  # 输出:['blue', 'green', 'red', 'yellow']

上述代码创建了一个集合colors,并使用sorted()函数对其进行排序。sorted_colors将保存排序后的列表。

需要注意的是,sorted()函数返回一个新的已排序列表,而不会修改原始列表。如果要修改原始列表,可以在排序后将新列表再赋值给原始变量。

除了使用关键字参数key进行排序外,sorted()函数还可以接受其他可选的参数,如reverse用于指定逆序排序。

总结:sorted()函数是用于对Python列表进行排序的强大函数。只需要传入一个可迭代对象,就可以返回一个排序后的新列表。可以通过指定关键字参数key来指定排序的方式,或者使用其他可选参数来控制排序的行为。