在Python中,对二维数组进行排序可以通过多种方式实现,以下是几种常见的方法:
使用内置的`sorted()`函数
```python
arr = [[3, 2], [1, 4], [5, 6]]
sorted_arr = sorted(arr, key=lambda x: x) 按第一列排序
print(sorted_arr) 输出: [[1, 4], [3, 2], [5, 6]]
使用`numpy`库的`argsort()`函数
```python
import numpy as np
arr = np.array([[3, 2], [1, 4], [5, 6]])
sorted_indices = arr[:, 0].argsort() 按第一列排序的索引
sorted_arr = arr[sorted_indices] 根据索引重新排列数组
print(sorted_arr) 输出: [[1 4]
[3 2]
[5 6]]
使用`pandas`库
```python
import pandas as pd
arr = pd.DataFrame([[3, 2], [1, 4], [5, 6]])
sorted_arr = arr.sort_values(by=arr.columns) 按第一列排序
print(sorted_arr) 输出: 01
14
23
06
12
25
Name: 0, dtype: int64
自定义排序函数
```python
def sort_by_column(arr, column):
return sorted(arr, key=lambda x: x[column])
matrix = [[5, 2, 3], [1, 7, 6], [4, 8, 9]]
sorted_matrix = sort_by_column(matrix, 0) 按第一列排序
print(sorted_matrix) 输出: [[1 7 6]
[4 8 9]
[5 2 3]]
使用`sort()`方法
```python
matrix = [[3, 1, 4], [1, 5, 9], [2, 6, 5]]
matrix.sort(key=lambda x: x) 按第一列排序
print(matrix) 输出: [[1 5 9]
[2 6 5]
[3 1 4]]
复合排序
```python
import numpy as np
data = np.array([[1, 2, 3, 4, 5], [1, 2, 3, 6, 7], [2, 3, 4, 5, 7], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]])
index = np.lexsort([data[:, 2], data[:, 1], data[:, 0]]) 先按第三列,再按第二列,最后按第一列排序
row_col_sorted = data[index] 根据排序索引重新排列数组
print(row_col_sorted)
以上方法可以帮助你根据不同的需求对二维数组进行排序。如果你需要更复杂的排序规则,比如多列排序或者降序排序,可以相应地调整`key`参数或者`reverse`参数