Python中的sorted()函数——排序功能及示例
发布时间:2023-12-02 20:34:48
Python中的sorted()函数是一个内置函数,主要用于对列表、元组、字典等可迭代对象进行排序。sorted()函数会返回一个新的排好序的可迭代对象,而不会修改原始对象。
sorted(iterable, key=None, reverse=False)
参数说明:
- iterable:需要排序的可迭代对象,如列表、元组等。
- key:可选参数,用于指定排序的规则。默认为None,表示按照元素的原始顺序排序。如果指定了key参数,会根据key函数的返回值来进行排序。
- reverse:可选参数,用于指定是否反向排序。默认为False,表示升序排序。
下面我们来看一些示例:
1. 对列表进行排序
numbers = [5, 2, 9, 1, 7] sorted_numbers = sorted(numbers) print(sorted_numbers) # [1, 2, 5, 7, 9]
2. 对元组进行排序
fruits = ('banana', 'apple', 'orange', 'pear')
sorted_fruits = sorted(fruits)
print(sorted_fruits) # ['apple', 'banana', 'orange', 'pear']
3. 对字典进行排序
ages = {'Alice': 25, 'Bob': 18, 'Charlie': 36, 'David': 30}
sorted_ages = sorted(ages)
print(sorted_ages) # ['Alice', 'Bob', 'Charlie', 'David']
注意,对字典排序时,返回的是按照键进行排序的结果。
4. 指定排序规则
我们可以使用key参数来指定排序规则,它接受一个函数作为参数,这个函数会被用来获取每个元素的键值。
students = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 18},
{'name': 'Charlie', 'age': 20},
{'name': 'David', 'age': 30}
]
sorted_students = sorted(students, key=lambda s: s['age'])
print(sorted_students)
# [
# {'name': 'Bob', 'age': 18},
# {'name': 'Charlie', 'age': 20},
# {'name': 'Alice', 'age': 25},
# {'name': 'David', 'age': 30}
# ]
在以上示例中,我们通过lambda函数来指定排序规则为按照学生的年龄进行排序。
5. 反向排序
我们可以设置reverse参数为True,来进行反向排序。
numbers = [5, 2, 9, 1, 7] reverse_sorted_numbers = sorted(numbers, reverse=True) print(reverse_sorted_numbers) # [9, 7, 5, 2, 1]
以上就是sorted()函数的基本功能和示例。它是一个非常常用的排序函数,可以灵活地根据不同的需求对不同的可迭代对象进行排序。注意,sorted()函数返回一个新的排序后的对象,原始对象的顺序并没有改变。
