Python中sorted()函数操作指南
发布时间:2023-08-26 09:17:31
sorted()函数是Python内置函数之一,用于对序列进行排序操作。它可以对列表、元组、字符串、字典以及其他可迭代对象进行排序。
sorted()函数的基本语法如下:
sorted(iterable, key=None, reverse=False)
参数解释:
1. iterable:表示要排序的序列,可以是列表、元组、字符串等。
2. key:可选参数,用于指定一个函数,该函数将作用于序列中的每个元素,根据元素的某个属性进行排序。默认为None,表示直接比较元素本身。
3. reverse:可选参数,表示排序后的结果是否按降序排列。默认为False,表示按升序排列。
使用sorted()函数可以对列表进行排序,示例如下:
numbers = [5, 1, 3, 2, 4] sorted_numbers = sorted(numbers) print(sorted_numbers) # [1, 2, 3, 4, 5]
使用sorted()函数对字符串进行排序,示例如下:
string = "python" sorted_string = sorted(string) print(sorted_string) # ['h', 'n', 'o', 'p', 't', 'y']
通过传递key参数,可以对序列中的元素的某个属性进行排序。例如,对一个列表中的字典按照某个key进行排序,示例如下:
students = [
{"name": "Alice", "age": 23},
{"name": "Bob", "age": 20},
{"name": "Charlie", "age": 25}
]
sorted_students = sorted(students, key=lambda s: s["age"])
print(sorted_students)
上述代码会根据学生的年龄进行排序,输出结果如下:
[{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 23}, {'name': 'Charlie', 'age': 25}]
还可以通过传递reverse参数,对排序结果进行降序排列。例如,对一个列表进行降序排序,示例如下:
numbers = [5, 1, 3, 2, 4] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers) # [5, 4, 3, 2, 1]
需要注意的是,sorted()函数对原始序列没有进行修改,而是返回一个新的排好序的列表。原始序列的顺序并没有改变。
总结来说,sorted()函数是Python中非常常用的一个排序函数。它可以对列表、元组、字符串等序列进行排序,可以根据元素的某个属性进行排序,还可以按照升序或降序排列。熟练掌握sorted()函数的使用,可以提高对序列排序的效率。
