要在 Python 中获得一组数从大到小排序的索引,你可以使用 NumPy 库的 argsort 方法,并结合 - 符号来实现降序排序。argsort 方法返回的是数组元素从小到大的索引值,因此我们可以通过加上负号 - 来使其变成从大到小的顺序。
下面是具体的步骤和示例代码:
1. 导入 NumPy 模块。
2. 创建一个 NumPy 数组。
3. 使用 - 符号使数组元素变为负数。
4. 使用 argsort 方法得到从大到小排序的索引。
5. 再次使用 - 符号将索引对应的元素变回原来的正数。
下面是具体的代码实现:
import numpy as np
# 示例数据
data = np.array([10, 5, 8, 3, 7])
# 获取从大到小排序的索引
sorted_indices = (-data).argsort()
# 打印排序后的索引
print("Sorted Indices (Descending Order):", sorted_indices)
现在让我们运行这段代码来看看结果:
import numpy as np
# 示例数据
data = np.array([10, 5, 8, 3, 7])
# 获取从大到小排序的索引
sorted_indices = (-data).argsort()
# 打印排序后的索引
print("Sorted Indices (Descending Order):", sorted_indices)
执行代码:
import numpy as np
# 示例数据
data = np.array([10, 5, 8, 3, 7])
# 获取从大到小排序的索引
sorted_indices = (-data).argsort()
# 打印排序后的索引
print("Sorted Indices (Descending Order):", sorted_indices)
Sorted Indices (Descending Order): [0 2 4 1 3]
结果表明,原始数组 [10, 5, 8, 3, 7] 的从大到小排序的索引为 [0, 2, 4, 1, 3],这意味着原数组中最大的数位于索引 0,其次是索引 2 的数,以此类推。
这样我们就得到了从大到小排序的索引。