sorted函數是一個內置函數,用于對可迭代對象進行排序。
用法: sorted(iterable, key=None, reverse=False)
參數說明:
返回值: 返回一個新的已排序的列表,不改變原可迭代對象。
示例:
對列表進行排序: 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]
對字符串進行排序: text = “python” sorted_text = sorted(text) print(sorted_text) # 輸出:[‘h’, ‘n’, ‘o’, ‘p’, ‘t’, ‘y’]
使用key參數進行自定義排序: students = [ {“name”: “Alice”, “age”: 20}, {“name”: “Bob”, “age”: 18}, {“name”: “Charlie”, “age”: 22} ] sorted_students = sorted(students, key=lambda x: x[“age”]) print(sorted_students) # 輸出:[{“name”: “Bob”, “age”: 18}, {“name”: “Alice”, “age”: 20}, {“name”: “Charlie”, “age”: 22}]