一文搞懂Python sorted() 函数

sorted() 是 Python 中用于排序的内置函数,它能够对各种可迭代对象进行排序并返回一个新的有序列表。与列表的 sort() 方法不同,sorted() 不会修改原对象,而是返回一个新的排序后的列表。

一、基本语法

sorted(iterable, *, key=None, reverse=False)

参数说明:

  • iterable:要排序的可迭代对象(列表、元组、字符串、字典、集合等)
  • key:指定排序依据的函数(默认为 None,即直接比较元素本身)
  • reverse:排序顺序,False 表示升序(默认),True 表示降序

二、基础用法

2.1 对列表排序

numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出: [1, 1, 2, 3, 4, 5, 9]
print(numbers)         # 输出: [3, 1, 4, 1, 5, 9, 2] (原列表不变)

2.2 对字符串排序

text = "python"
sorted_text = sorted(text)
print(sorted_text)  # 输出: ['h', 'n', 'o', 'p', 't', 'y']
print(''.join(sorted_text))  # 输出: "hnopty"

2.3 对元组排序

tuples = [(1, 'b'), (2, 'a'), (1, 'a')]
sorted_tuples = sorted(tuples)
print(sorted_tuples)  # 输出: [(1, 'a'), (1, 'b'), (2, 'a')]

三、高级用法

3.1 使用 key 参数自定义排序

key 参数接受一个函数,该函数将应用于每个元素,然后根据函数返回的结果进行排序。

按字符串长度排序
words = ["banana", "pie", "apple", "orange"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # 输出: ['pie', 'apple', 'banana', 'orange']
按字典的值排序
students = [
    

你可能感兴趣的:(python编程,python,开发语言,学习,笔记)