首页 文章资讯内容详情

Python中的Sorted()函数

2026-06-04 1 花语

在本教程中,我们将学习Python中的sorted()函数。

函数sorted()用于对可迭代对象进行升序降序排序。我们甚至可以根据不同的键和值对字典列表进行排序。让我们充分利用sorted()函数。

排序()函数是不是一个就地算法类似的排序方法。

默认sorted()

默认情况下,sorted()函数将对可迭代对象进行升序排序。让我们来看一个例子。

示例

# initializing a list numbers = [4, 3, 5, 1, 2] # sorting the numbers sorted_numbers = sorted(numbers) # printing the sorted_numbers print(sorted_numbers)

输出结果

如果运行上面的代码,则将得到以下结果。

[1, 2, 3, 4, 5]

反向排序()

我们可以将参数reverse设置为True,以对可迭代对象进行降序排序。让我们来看一个例子。

示例

# initializing a list numbers = [4, 3, 5, 1, 2] # sorting the numbers sorted_numbers = sorted(numbers, reverse=True) # printing the sorted_numbers print(sorted_numbers)

输出结果

如果运行上面的代码,则将得到以下结果。

[5, 4, 3, 2, 1]

带有sorted()的关键参数

函数sorted()将采用另一个称为key的可选参数。参数是告诉sorted()必须对列表进行排序的值。

假设我们有一个词典列表。我们必须根据某个值对字典列表进行排序。在这种情况下,我们将key作为参数传递给函数,该函数返回一个必须对字典列表进行排序的特定值。

示例

# initializing a list numbers = [{a: 5}, {b: 1, a: 1}, {c: 3, a: 3}, {d: 4, a: 4}, {e a: 2}] # sorting the list of dict based on values sorted_dictionaries = sorted(numbers, key= lambda dictionary: dictionary[a]) # printing the numbers print(sorted_dictionaries)

输出结果

如果运行上面的代码,则将得到以下结果。

[{b: 1, a: 1}, {e: 2, a: 2}, {c: 3, a: 3}, {d: 4, a: 4}, {a:

结论

如果您对本教程有任何疑问,请在评论部分中提及。