You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据随机生成的NumPy年龄数组对分数数组排序

用NumPy根据年龄数组排序分数数组的解决方案

没问题,这个需求用NumPy完全可以轻松实现,而且不管是随机生成的还是固定值的数组,解法都是通用的,不用担心随机元素的适配问题!

第一步:修正数组生成代码(可选但推荐)

首先注意一下,你用到的random.random_integers在NumPy的新版本中已经被弃用了,建议替换成random.randint来生成随机整数,用法几乎一致:

import numpy as np

# 生成(1,200)的二维数组,也可以直接生成一维数组更方便
age = np.random.randint(18, 41, size=(1, 200))  # 注意randint是左闭右开,所以上限要写41才能包含40
marks = np.random.randint(0, 101, size=(1, 200))

如果觉得二维数组操作麻烦,也可以直接生成一维数组:

age = np.random.randint(18, 41, size=200)
marks = np.random.randint(0, 101, size=200)

第二步:核心排序逻辑

NumPy的argsort()方法是解决这个问题的关键,它会返回数组元素从小到大排序后的索引位置。我们只需要先获取年龄数组的排序索引,再用这个索引去重新排列年龄和分数数组即可:

针对二维数组的情况:

# 获取年龄数组的排序索引(因为是二维数组,要指定axis=1来按行排序)
sort_indices = age.argsort(axis=1)

# 根据索引排序年龄和分数数组
sorted_age = np.take_along_axis(age, sort_indices, axis=1)
sorted_marks = np.take_along_axis(marks, sort_indices, axis=1)

# 打印前10个元素看效果(和你给的示例格式一致)
print("#random student ages")
print(age[0][:10])
print("#random student marks")
print(marks[0][:10])
print("#sorted ages according to ages")
print(sorted_age[0][:10])
print("#sorted marks according to ages")
print(sorted_marks[0][:10])

针对一维数组的情况(更简洁):

# 获取排序索引
sort_indices = age.argsort()

# 直接用索引排序
sorted_age = age[sort_indices]
sorted_marks = marks[sort_indices]

# 打印示例
print("#random student ages")
print(age[:10])
print("#random student marks")
print(marks[:10])
print("#sorted ages according to ages")
print(sorted_age[:10])
print("#sorted marks according to ages")
print(sorted_marks[:10])

为什么随机生成的元素也适用?

这个方法的核心是基于索引的排序,不管数组里的元素是随机生成的还是固定值,argsort()都会正确返回从小到大的排序索引,再用这个索引去映射分数数组,就能保证分数和排序后的年龄一一对应,完全不受元素是否随机的影响。

比如你给出的示例数据,用这个方法运行后,就能得到和你期望完全一致的排序结果。

内容的提问来源于stack exchange,提问作者Hamza Ebrahim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:55:54