下面是一个示例代码,演示如何按从左到右的最小值对一个Numpy ndarray的类和坐标进行排序:
import numpy as np
# 创建一个示例的Numpy ndarray
arr = np.array([[5, 3, 1],
[4, 2, 6],
[7, 9, 8]])
# 创建一个包含类和坐标的结构化数组
dtype = [('value', int), ('row', int), ('col', int)]
data = np.empty(arr.shape[0] * arr.shape[1], dtype=dtype)
# 将数据和坐标填充到结构化数组中
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
data[i * arr.shape[1] + j] = (arr[i, j], i, j)
# 按照最小值排序
sorted_data = np.sort(data, order='value')
# 输出排序结果
for item in sorted_data:
print(item)
输出结果:
(1, 0, 2)
(2, 1, 1)
(3, 0, 1)
(4, 1, 0)
(5, 0, 0)
(6, 1, 2)
(7, 2, 0)
(8, 2, 2)
(9, 2, 1)
在这个示例中,我们首先创建一个结构化数组,其中包含了元素值、行索引和列索引。然后,我们将数组的值和坐标填充到结构化数组中。接下来,我们使用Numpy的sort
函数对结构化数组按照最小值进行排序。最后,我们遍历排序后的结构化数组,输出排序结果。