【发布时间】:2017-02-04 17:19:43
【问题描述】:
假设我有两个列表,一个是学生 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 等),我想按分数(升序)排序学生 ID,预期输出为 #[1,3,4,2,10,5]。
我目前的解决方案有点天真,它设置了一个学生班级。在 Python 2.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(students)->students.sort()或者for i in sorted(students)。 -
实际上,上面链接的解决方案(关于
sorted()vs.sort())没有回答这个问题。就是这个:stackoverflow.com/questions/6618515/…
标签: python python-2.7 sorting