如何使用Python的sorted函数
发布时间:2023-07-02 18:52:46
sorted函数是Python中内置的一个用于排序的函数。可以通过sorted函数对列表、元组、字典、集合以及其他可迭代对象进行排序。
sorted函数的基本用法是:
sorted(iterable[, key][, reverse])
其中,iterable为待排序的可迭代对象,key为可选的用于指定排序规则的函数,reverse为可选的用于指定排序顺序的布尔值,默认为False(升序排序)。
下面对sorted函数的用法进行详细说明:
1. 对列表进行排序:
numbers = [5, 3, 8, 1, 2] sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出[1, 2, 3, 5, 8]
2. 对元组进行排序:
numbers = (5, 3, 8, 1, 2) sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出[1, 2, 3, 5, 8]
3. 对字典的键进行排序:
scores = {"Alice": 90, "Bob": 80, "Charlie": 95, "David": 85}
sorted_names = sorted(scores)
print(sorted_names) # 输出['Alice', 'Bob', 'Charlie', 'David']
4. 对字典的值进行排序:
scores = {"Alice": 90, "Bob": 80, "Charlie": 95, "David": 85}
sorted_scores = sorted(scores, key=scores.get)
print(sorted_scores) # 输出['Bob', 'David', 'Alice', 'Charlie']
5. 对集合进行排序:
fruits = {"apple", "banana", "orange", "pear"}
sorted_fruits = sorted(fruits)
print(sorted_fruits) # 输出['apple', 'banana', 'orange', 'pear']
6. 指定排序规则和顺序:
numbers = [5, 3, 8, 1, 2] sorted_numbers = sorted(numbers, reverse=True) # 降序排序 print(sorted_numbers) # 输出[8, 5, 3, 2, 1]
7. 使用lambda函数指定排序规则:
students = [("Alice", 90), ("Bob", 80), ("Charlie", 95), ("David", 85)]
sorted_students = sorted(students, key=lambda x: x[1]) # 根据成绩排序
print(sorted_students) # 输出[('Bob', 80), ('David', 85), ('Alice', 90), ('Charlie', 95)]
总结起来,sorted函数可以方便地对Python中的各种可迭代对象进行排序。通过指定key参数可以自定义排序规则,通过指定reverse参数可以选择排序顺序。利用这些功能,可以很方便地完成各种排序需求。
