假设我有两个列表,一个是student ID studentID=[1,4,2,3,5,10]
,另一个是列表的同一索引中每个学生的相关分数studentScore=[1.0, 2.5, 3.0, 2.1, 5.0, 4.5]
(这意味着ID为1的学生的分数为1.0,ID为4的学生的分数为2.5,等等),我想按分数排序student ID(升序),预期的输出是#[1,3,4,2,10,5]
。你知道吗
我目前的解决方案有点幼稚,设置了一个学生班。在Python2.7中,想知道是否有其他方法可以根据相关分数获得学生ID的排序结果,而无需使用其他类来设置它们(两个列表)的关系?你知道吗
把我现在的代码贴在下面
class Student:
def __init__(self, ID, score):
self.ID = ID
self.score = score
def __cmp__(self, other):
return cmp(self.score, other.score)
studentID=[1,4,2,3,5,10]
studentScore=[1.0, 2.5, 3.0, 2.1, 5.0, 4.5]
students = []
for i in range(len(studentID)):
students.append(Student(studentID[i], studentScore[i]))
sorted(students)
for i in students:
print i.ID
# expect output: sorted student ID by student score
#[1,3,4,2,10,5]
解决方案实际上是可以的,但是对于像这样的小任务,您可以使用
sorted
的key
kwarg来代替声明新类:告诉
sorted
键是每对中的第二项,即分数。你知道吗解决方案
收益率
解释
调用
zip(scores, sid)
根据项的位置将两个列表连接到一个元组列表中:对
sorted(...)
的调用按每个元组的第一项对压缩元组列表进行排序:封闭列表理解
[stid for (score, stid) in ...]
然后只从每个元组中提取第二个参数(这里称为stid
),并在保持新顺序的同时创建一个新列表:这一行将根据分数对分数和ID进行排序:
相关问题 更多 >
编程相关推荐