概念解释
sorted()
是Python内置的一个函数,用于对可迭代对象进行排序。它返回一个新的排序后的列表,而不会修改原来的可迭代对象。
基本语法
sorted(iterable, key=None, reverse=False)
iterable
:需要排序的可迭代对象,例如列表、元组、字符串等。key
:可选参数,用于指定一个函数,该函数会在每个元素比较之前调用。例如,可以使用key=len
来按长度排序。reverse
:可选参数,如果设置为True
,则按降序排序;如果设置为False
(默认值),则按升序排序。
编程示例
示例1:对列表进行排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
示例2:对字符串进行排序
word = "python"
sorted_word = sorted(word)
print(sorted_word) # 输出: ['h', 'n', 'o', 'p', 't', 'y']
示例3:按长度对列表中的字符串进行排序
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=len)
print(sorted_words) # 输出: ['date', 'apple', 'banana', 'cherry']
示例4:按降序排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # 输出: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
示例5:对字典按值排序
students = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}
sorted_students = sorted(students, key=lambda x: students[x])
print(sorted_students) # 输出: ['Charlie', 'Alice', 'David', 'Bob']
示例6:对复杂对象进行排序
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
students = [
Student('Alice', 85),
Student('Bob', 92),
Student('Charlie', 78),
Student('David', 88)
]
sorted_students = sorted(students, key=lambda x: x.score)
for student in sorted_students:
print(f"{student.name}: {student.score}")
输出:
Charlie: 78
Alice: 85
David: 88
Bob: 92
总结
sorted()
函数是一个非常强大且灵活的工具,适用于各种排序需求。通过 key
参数,可以实现复杂的排序逻辑。