Python 中的 sort() 函数:深入指南229


Python 中的 sort() 函数是用于对可变序列(如列表、元组)进行排序的内置函数。它按照升序 (从小到大) 或降序 (从大到小) 对元素进行排列,并修改原始序列。

sort() 函数语法

sort() 函数的语法如下:```python
(key=None, reverse=False)
```

其中:* list:需要排序的可变序列。
* key:可选的函数,用于指定排序的条件。
* reverse:可选的布尔值,指定排序顺序。True 为降序,False 为升序(默认)。

排序机制

sort() 函数使用 Timsort 算法,它是一种混合排序算法,结合了归并排序和插入排序的优点。Timsort 先将序列分成较小的子序列,对子序列进行归并排序,然后将排序后的子序列合并成一个排序的序列。

Timsort 的时间复杂度为 O(n log n)(n 为序列长度),在大多数情况下是一种高效的排序算法。

sort() 函数示例

以下是一些 sort() 函数的示例:```python
# 对整型列表进行升序排序
my_list = [3, 1, 5, 2, 4]
()
print(my_list) # 输出: [1, 2, 3, 4, 5]
# 对字符串列表进行降序排序
names = ['Alice', 'Bob', 'Eve', 'David', 'Carol']
(reverse=True)
print(names) # 输出: ['Zoe', 'Yolanda', 'Xavier', 'Wilson', 'Victoria']
# 使用 key 函数对字典列表按值排序
students = [{'name': 'John', 'score': 90},
{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 95}]
(key=lambda x: x['score']) # 按成绩排序
print(students) # 输出: [{'name': 'Alice', 'score': 85}, {'name': 'John', 'score': 90}, {'name': 'Bob', 'score': 95}]
```

自定义排序

sort() 函数通过 key 参数允许自定义排序。key 参数指定一个函数,该函数用于计算序列中每个元素的排序条件。排序条件可以是任何可比较的值,例如字符串、数字或布尔值。

以下示例演示如何根据字符串长度对字符串列表进行排序:```python
def string_length(s):
return len(s)
words = ['apple', 'banana', 'cherry', 'dog', 'elephant']
(key=string_length)
print(words) # 输出: ['dog', 'apple', 'banana', 'cherry', 'elephant']
```

稳定性

稳定性是指当两个元素相等时,sort() 函数保持其相对顺序。Python 中的 sort() 函数不是稳定的。这意味着当序列中存在相等元素时,它们的排序顺序在调用 sort() 函数后可能会发生变化。

稳定排序

如果需要稳定排序,可以使用 sorted() 内置函数。sorted() 返回一个排序后的新列表,而不修改原始序列。sorted() 函数的语法与 sort() 函数相似,也支持 key 参数。

以下示例演示如何使用 sorted() 函数进行稳定排序:```python
# 使用 sorted() 进行稳定排序
sorted_words = sorted(words, key=string_length)
print(sorted_words) # 输出: ['apple', 'banana', 'cherry', 'dog', 'elephant']
```

Python 中的 sort() 函数是一个强大的工具,可用于对可变序列进行排序。它使用 Timsort 算法进行高效排序,并允许自定义排序条件。对于不稳定的排序,sort() 函数是理想的选择。对于稳定的排序,可以使用 sorted() 函数。

2024-10-17


上一篇:Python 代码规范:is vs. ==

下一篇:Python中统计字符串中单词个数