Python 排序函数详解:sorted()、sort() 与 numpy.argsort()
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]]

