sorted()`是非常强大的排序工具,主要体现在:
- 内置参数强大,基本可以处理所有常见排序需求
- 可以处理Python中几乎一切可迭代对象(iterable)的排序
语法
sorted(iterable, key=None, reverse=False)
内置参数
iterable
可迭代对象:
- 列表(list)
- 元组(tuple)
- 字典(dict,对key排序)
- 字符串(str,按字符的 Unicode 编码排序)
- 集合(set)
# list
numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出: [1, 1, 3, 4, 5, 9]
key
函数,用来提取待排序元素的关键字(排序依据)
常见 key
函数:
len
(按长度排序)
str.lower
(忽略大小写排序)
lambda
函数(自定义)
compare
函数转换为key
函数(cmp_to_key()
)
# key = len
words = ["apple", "banana", "cherry", "date"]
sorted_by_length = sorted(words, key=len) # 根据长度排序
print(sorted_by_length) # 输出: ['date', 'apple', 'banana', 'cherry']
# key = lambda x: ...
people = [('Alice', 25), ('Bob', 20), ('Charlie', 30)]
sorted_people = sorted(people, key=lambda x: x[1]) # 按年龄排序
print(sorted_people) # 输出: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]
reverse
布尔值,用于控制排序的顺序。
默认值是 False
,表示升序排序。如果设置 reverse=True
,则会按降序排序。
numbers = [3, 1, 4, 1, 5]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # 输出:[5, 4, 3, 1, 1]
返回值
sorted()
会创建一个列表,并返回该列表
因此处理字符串时,可能需要从列表中再次连接,例如:
word = "python" sorted_word = sorted(word) print(sorted_word) # 输出: ['h', 'n', 'o', 'p', 't', 'y'] print(''.join(sorted_word)) # 输出: "hnopty"
与sort()
函数的不同
sort()
只处理列表,sorted()
可以处理大多数可迭代对象sort()
是原地处理,不返回,sorted()
是创建新列表并返回- 用法上,
lst.sort()
和sorted_list = sorted(lst)
相同点:排序算法、参数设置都一致,都支持key
和reverse
参数
排序算法
Timsort,一种排序算法,结合了归并排序和插入排序的思想,尤其适用于在数据已经部分有序的情况下。另外,当两个元素具有相同的排序键时,它们在排序后的顺序与原始顺序相同。
时间复杂度: O ( n l o g n ) O(n log n) O(nlogn)
空间复杂度: O ( n ) O(n) O(n)
最坏时间复杂度也是O(n log n),最好时间是O(n),也即全都有序的情况