Python2.7 advi列表排序

2024-04-20 03:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个列表,一个是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]

Tags: selfid列表排序defstudent学生分数
3条回答

解决方案实际上是可以的,但是对于像这样的小任务,您可以使用sortedkeykwarg来代替声明新类:

studentID=[1,4,2,3,5,10]
studentScore=[1.0, 2.5, 3.0, 2.1, 5.0, 4.5]
combined = zip(studentID, studentScore)
comb_sorted = sorted(combined, key=lambda pair: pair[1])
sortedID, sortedScore = list(zip(*comb_sorted))

告诉sorted键是每对中的第二项,即分数。你知道吗

解决方案

sid = [1, 4, 2, 3, 5, 10]
scores = [1.0, 2.5, 3.0, 2.1, 5.0, 4.5]

print([stid for (score, stid) in sorted(zip(scores, sid))])

收益率

[1, 3, 4, 2, 10, 5]

解释

调用zip(scores, sid)根据项的位置将两个列表连接到一个元组列表中:

[(1.0, 1), (2.5, 4), (3.0, 2), (2.1, 3), (5.0, 5), (4.5, 10)]

sorted(...)的调用按每个元组的第一项对压缩元组列表进行排序:

[(1.0, 1), (2.1, 3), (2.5, 4), (3.0, 2), (4.5, 10), (5.0, 5)]

封闭列表理解[stid for (score, stid) in ...]然后只从每个元组中提取第二个参数(这里称为stid),并在保持新顺序的同时创建一个新列表:

[1, 3, 4, 2, 10, 5]

这一行将根据分数对分数和ID进行排序:

studentScore,studentID=zip(*sorted(zip(studentScore,studentID)))

相关问题 更多 >