数组中按列排序,举个例子
时间: 2023-05-24 15:06:40 浏览: 51
假设数组如下:
```python
arr = [
[3, 2, 1],
[6, 5, 4],
[9, 8, 7]
]
```
如果按照每行排序,结果为:
```python
arr.sort()
print(arr)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
如果按照每列排序,结果为:
```python
arr = [
[3, 2, 1],
[6, 5, 4],
[9, 8, 7]
]
# 借助 zip 函数将每列组成新的列表
new_arr = zip(*arr)
new_arr = [list(x) for x in new_arr]
# 对新列表每个子列表排序
for sub_arr in new_arr:
sub_arr.sort()
# 重新组合成二维列表
arr = [list(x) for x in zip(*new_arr)]
print(arr)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
相关问题
c++数组排序,举个例子说明
当你需要对C++数组进行排序时,你可以使用标准库中的 `std::sort` 函数。这个函数可以对数组进行升序或降序排序。下面是一个示例代码,展示了如何使用 `std::sort` 对整型数组进行升序排序:
```cpp
#include <iostream>
#include <algorithm> // 包含了 std::sort 函数
using namespace std;
int main() {
int arr[] = {5, 2, 9, 1, 7}; // 定义一个整型数组
int n = sizeof(arr) / sizeof(arr[0]); // 计算数组的长度
sort(arr, arr + n); // 使用 std::sort 对数组进行升序排序
cout << "升序排序后的数组:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
运行以上代码,输出将是:`升序排序后的数组:1 2 5 7 9`。
在上述示例中,我们首先定义了一个整型数组 `arr`,然后通过 `sizeof(arr) / sizeof(arr[0])` 计算数组的长度,以便在 `std::sort` 函数中指定排序范围。然后,我们使用 `std::sort` 函数对数组进行升序排序。最后,我们使用一个循环打印排序后的数组。
python多维数组按列排序
以下是两种Python多维数组按列排序的例子:
1. 使用np.lexsort()函数按照指定的列顺序排序多维数组:
```python
import numpy as np
arr = np.array([[6, 3, 6, 4], [3, 1, 2, 0], [3, 1, 8, 3]]).transpose()
print('%=============原始数据(4行3列)=================')
print(arr)
arrSortedIndex = np.lexsort((arr[:, 2], arr[:, 1], arr[:, 0]))
print('%======按照x优先,y次级,z最后规则排序后=======')
print(arr[arrSortedIndex, :])
arrSortedIndex = np.lexsort((arr[:, 0], arr[:, 1], arr[:, 2]))
print('%======按照z优先,y次级,x最后规则排序后=======')
print(arr[arrSortedIndex, :])
```
2. 使用np.lexsort()函数默认排序规则排序二维数组:
```python
import numpy as np
arr = np.array([[6, 3, 6, 4], [3, 1, 2, 0]])
print('%=============原始数据(二维数组)===============')
print(arr)
arrSortedIndex = np.lexsort(arr)
print('%=================默认排序规则=================')
print(arr[:, arrSortedIndex])
```