问题描述
这是我第一次使用数组,一般来说我是 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,[19,2022],[24,2018]
]
我首先想到的是,我将如何一起检索姓名和班级名册?
我做到了: 姓名 + class_roster
然后需要获取花名册中年龄最大的人的索引,并从姓名列表中检索他们的名字。
参考这个link
我尝试过:出现“无法分配给操作员”错误
names + class_roster = ndarray
ndarray.ptp([axis,out])
在我得到上面的输出最年长的人和他们的名字后,我将如何翻转代码以显示最年轻的人的名字?
解决方法
分配的工作方式相反:
ndarray = names + class_roster
另请注意,您目前没有任何 numpy 数组。 对于您的问题:
names = ['Alice','Edward','Timothy','James','Brandon','Mark']
class_roster = [
[22,2021],[23,2020],[21,[19,2022],[24,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 库跟踪所有这些信息。
,既然你想使用 numpy,首先将你的列表声明为数组:
# Names of a group of students
names = np.array(['Alice','Mark'])
# Age and graduation year of the above students
class_roster = np.array([
[22,2018]
])
使用 numpy.argsort 从 class_roster
获取排序索引:
indx = np.argsort(class_roster[:,0])
(如果您不熟悉这种索引编制,您可以read more了解它)
最后,使用这些索引对数组进行排序 names
:
names[indx]
# array(['James','Alice','Mark','Brandon'],dtype='<U7')
请注意,我避免合并这些数组。如果这对您很重要,您可能需要使用 numpy.hstack:
np.hstack([names[:,None],class_roster])
#array([['Alice','22','2021'],['Edward','23','2020'],['Timothy','21',['James','19','2022'],['Brandon','24',['Mark','2018']],dtype='<U21')
说了这么多,对于这个特定的应用程序,pandas
可能是一个更适合使用的包,正如@joostblack 所提到的。您可能会注意到,通过合并,您可以将 numpy 数组转换为不同的类型,因此并没有太大帮助。