当前位置:首页 > 随笔 > 正文内容

Python 排序函数详解:sorted()、sort() 与 numpy.argsort()

访客 随笔 2026年11月4日 1

Python 提供了内置的排序功能,主要通过 sorted() 函数和列表对象的 sort() 方法实现。此外,NumPy 库也提供了 argsort() 函数,用于获取数组的索引排序。

1. sorted() 函数与 list.sort() 方法

sorted() 是一个内置函数,可以对任何可迭代对象(如列表、元组、字典、字符串等)进行排序,并返回一个新的已排序列表。而 list.sort() 是列表对象的一个方法,它会直接在原地修改列表,不返回任何值。

基本用法

对于升序排序,可以直接调用 sorted() 或 sort()。


original_list = [5, 2, 3, 1, 4]
# 使用 sorted() 函数,返回新列表
sorted_list = sorted(original_list)
print(f"Sorted list using sorted(): {sorted_list}")
# 输出: Sorted list using sorted(): [1, 2, 3, 4, 5]

# 使用 list.sort() 方法,原地修改列表
original_list.sort()
print(f"Original list after sort(): {original_list}")
# 输出: Original list after sort(): [1, 2, 3, 4, 5]
    

重要提示: sort() 方法仅适用于列表。而 sorted() 函数适用于所有可迭代序列,并且总是返回一个列表。

对字典进行排序时,默认按键排序:


my_dict = {8: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}
sorted_keys = sorted(my_dict)
print(f"Sorted keys of dictionary: {sorted_keys}")
# 输出: Sorted keys of dictionary: [2, 3, 4, 5, 8]
    

sorted() 函数的参数

sorted() 函数接受以下可选参数:

  • iterable: 必需,要排序的可迭代对象。
  • key: 可选,一个函数,用于在比较之前为每个元素生成一个"排序键"。
  • reverse: 可选,一个布尔值。如果设置为 True,则按降序排序;默认为 False(升序)。
  • cmp (Python 2.x): Python 3.x 中已移除。在 Python 2.x 中,这是一个比较函数,接受两个参数并返回 -1、0 或 1。

使用 key 参数

key 参数允许你指定一个函数,该函数将在对每个元素进行比较前被调用。这对于忽略大小写或按特定属性排序非常有用。


# 忽略字符串大小写进行排序
words = "This is a test string from Andrew".split()
sorted_words = sorted(words, key=str.lower)
print(f"Words sorted ignoring case: {sorted_words}")
# 输出: Words sorted ignoring case: ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

# 对包含元组的列表按元组的第二个元素排序
list_of_tuples = [('david', 90), ('mary', 90), ('sara', 80), ('lily', 95)]
sorted_by_score = sorted(list_of_tuples, key=lambda item: item[1])
print(f"Tuples sorted by second element: {sorted_by_score}")
# 输出: Tuples sorted by second element: [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
    

使用 reverse 参数

通过设置 reverse=True 可以实现降序排序。


list_of_tuples = [('david', 90), ('mary', 90), ('sara', 80), ('lily', 95)]
# 按元组的第二个元素降序排序
descending_sorted_tuples = sorted(list_of_tuples, key=lambda item: item[1], reverse=True)
print(f"Tuples sorted by second element (descending): {descending_sorted_tuples}")
# 输出: Tuples sorted by second element (descending): [('lily', 95), ('david', 90), ('mary', 90), ('sara', 80)]
    

2. NumPy 的 argsort() 函数

numpy.argsort() 函数返回的是排序后数组元素的索引,而不是排序后的数组本身。这对于需要知道元素在排序后位置的场景非常有用。

一维数组


import numpy as np

# 一维数组
arr_1d = np.array([3, 1, 2])
indices_1d = np.argsort(arr_1d)
print(f"Original 1D array: {arr_1d}")
print(f"Indices for sorted 1D array: {indices_1d}")
# 输出: Indices for sorted 1D array: [1 2 0]

# 使用索引重新排列原数组
sorted_arr_1d = arr_1d[indices_1d]
print(f"Sorted 1D array using indices: {sorted_arr_1d}")
# 输出: Sorted 1D array using indices: [1 2 3]

# 降序排序索引
desc_indices_1d = np.argsort(-arr_1d)
print(f"Indices for descending sorted 1D array: {desc_indices_1d}")
# 输出: Indices for descending sorted 1D array: [0 2 1]
sorted_desc_arr_1d = arr_1d[desc_indices_1d]
print(f"Descending sorted 1D array using indices: {sorted_desc_arr_1d}")
# 输出: Descending sorted 1D array using indices: [3 2 1]
    

二维数组

对于二维数组,axis 参数指定了排序沿着哪个轴进行:

  • axis=0: 按列排序。
  • axis=1: 按行排序。

# 二维数组
arr_2d = np.array([[0, 3], [2, 2]])
print(f"\nOriginal 2D array:\n{arr_2d}")

# 按列排序 (axis=0)
indices_col_sort = np.argsort(arr_2d, axis=0)
print(f"Indices for column-wise sorted 2D array:\n{indices_col_sort}")
# 输出:
# Indices for column-wise sorted 2D array:
# [[0 1]
#  [1 0]]

# 按行排序 (axis=1)
indices_row_sort = np.argsort(arr_2d, axis=1)
print(f"Indices for row-wise sorted 2D array:\n{indices_row_sort}")
# 输出:
# Indices for row-wise sorted 2D array:
# [[0 1]
#  [0 1]]
    

相关文章

可以按小时收费的VPS

很多 VPS 提供商都支持 按小时计费(hourly billing),想短期试用 / 临时搭建节点、测试网络、短期项目等场景非常合适。下面是当前最主流且靠谱的按小时 VPS 选项,分别按不同需求场景整理: 1. Vultr(全球节点,包括日本) 按小时计费 可选机房:东京 / 大阪 / 洛杉矶 / 法兰克福 / 伦敦 … 支持 PayPal(部分情况),但更常用信用卡/PayPal+卡价格参考$...

在 iPhone 上下载国外App

地区/国家限制App Store 会根据 Apple ID 的国家或地区限制应用下载。如果你的 Apple ID 绑定的是中国大陆,就可能无法下载 OpenAI 官方的 ChatGPT 应用,因为它在大陆 App Store 不上架。解决办法:换成美国、加拿大、香港等地区的 Apple ID。或者在现有 Apple ID 上更改地区。注册一个国外 Apple ID(推荐)比如注册 美国区 Appl...

Node.js 中的异步编程:回调与 Promise

Node.js 是一个基于 JavaScript 构建的单线程、非阻塞运行环境,它通过异步编程机制来高效处理多个操作。在执行如文件读取、API 请求或数据库查询等任务时,Node.js 不会等待这些操作完成,而是使用回调函数和 Promise 来避免阻塞主线程。 回调方式实现异步 那么当异步操作完成后,Node.js 如何知道接下来要做什么呢?这就要用到 回调函数(callback)。 回调本质上...

Selenium自动化测试入门指南

Selenium自动化测试入门指南

什么是自动化测试? 自动化测试是指利用软件工具自动执行测试用例,模拟用户操作,如打开网页、点击链接、输入文本等,并验证结果是否符合预期。 其主要优点包括: 大幅减少人工成本 测试速度快 可以在非工作时间运行 支持持续集成和交付 然而,它也存在一些局限性,例如开发成本较高、不适合快速变化的项目、依赖稳定的UI界面等。 自动化测试的应用条件 适合引入自动化测试的情况包括: 手动测试耗时且需要大量...

Android 中 EventBus 的通信机制与实现原理深度解析

EventBus 核心设计思想 EventBus 是一个基于观察者模式的事件总线框架,广泛应用于 Android 平台以实现组件解耦。它通过中心化的消息分发机制,使不同层级、不同线程的对象能够以"发布-订阅"方式通信,避免了传统接口回调或广播带来的强依赖问题。 核心角色说明 事件(Event):任意 Java 对象,作为数据载体,如网络状态变更通知、用户登录信息等。 发布者(Publi...

二叉树基础操作实现(C语言)

二叉树基础操作实现(C语言)

二叉树遍历方法 以下为二叉树结构示例 前序访问实现: void traversePreOrder(TreeNode* node) { if (node == NULL) { printf("N "); return; } printf("%d ", node->value); trave...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。