首页 > 解决方案 > NumPy 的新手,如何对 ndarray 进行排序(不仅仅是整数)?

问题描述

这是我第一次使用数组,一般来说我是 python 新手。我尽了最大努力,很好奇是否有人可以纠正我的错误并让我知道我哪里出错了!谢谢

# Names of a group of students 
names = ['Alice', 'Edward', 'Timothy', 'James', 'Brandon', 'Mark']

# Age and graduation year of the above students
class_roster = [
    [22, 2021],
    [23, 2020],
    [21, 2021],
    [19, 2022],
    [24, 2020],
    [23, 2018]
]

我首先想到,我将如何一起检索姓名和班级名册?

我做了:名字+ class_roster

然后需要获取名册中最年长的人的索引并从名称列表中检索他们的姓名。

参考这个链接

我试过:出现“无法分配给操作员”错误

names + class_roster = ndarray

ndarray.ptp([axis, out])

在我得到上面输出最年长的人和他们的名字之后,我将如何在代码方面翻转它以显示最年轻的人的名字?

标签: pythonnumpynumpy-ndarray

解决方案


分配工作相反:

ndarray = names + class_roster

另请注意,您目前没有任何 numpy 数组。对于您的问题:

names = ['Alice', 'Edward', 'Timothy', 'James', 'Brandon', 'Mark']
class_roster = [
    [22, 2021],
    [23, 2020],
    [21, 2021],
    [19, 2022],
    [24, 2020],
    [23, 2018]
]

# combine names with class_roster
people = [ x for x in zip(names,class_roster)]

# search for oldest student
oldest_person = max(people,key=lambda x:x[1][0])[0]
print("the oldest person is ",oldest_person)

# search for the youngest student
youngest_person = min(people,key=lambda x:x[1][0])[0]
print("the youngest person is ",youngest_person)

最后,创建一个以姓名和年龄为属性的类人可能会更好。或者,您可以使用 Pandas 库跟踪所有这些信息。


推荐阅读