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

Python中的sorted函数: 对序列进行排序并返回新的排好序的列表

发布时间:2023-07-23 21:33:28

Python中的sorted函数是一个内置函数,可以对序列进行排序并返回一个新的排好序的列表。sorted函数的语法如下:sorted(iterable, key=None, reverse=False)

其中,iterable是要排序的序列,可以是列表、元组、字符串等可迭代对象;key是一个可选参数,用于指定一个函数,该函数将作用于每个元素,并根据函数的返回值进行排序;reverse也是一个可选参数,用于指定是否降序排序,默认为False,即升序排序。

sorted函数的返回值是一个新的排好序的列表,原来的序列不会被改变。

下面是一些示例:

1. 对列表进行排序:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出 [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]

2. 对字符串进行排序:

string = "hello world"
sorted_string = sorted(string)
print(sorted_string)  # 输出 [' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

3. 使用key参数排序:

students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78},
    {"name": "David", "score": 88}
]

sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
# 按照分数降序排序
print(sorted_students)
# 输出 [{'name': 'Bob', 'score': 92}, {'name': 'David', 'score': 88}, {'name': 'Alice', 'score': 85}, {'name': 'Charlie', 'score': 78}]

以上示例演示了不同情况下sorted函数的用法,可以看出sorted函数非常灵活,可以根据需要进行定制化的排序,能够处理各种类型的数据。

总之,sorted函数在Python中是非常常用的排序函数,它可以对序列进行排序并返回一个新的排好序的列表,同时还可以使用key参数进行自定义排序。无论是对数字、字符串,还是对复杂的数据结构进行排序,sorted函数都能够轻松应对。