【问题标题】:python 2.7 list sort for advice [duplicate]python 2.7列表排序以获取建议[重复]
【发布时间】: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


【解决方案1】:

解决方案

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]

【讨论】:

  • 酷,不知道zip这么厉害!
  • BTW jbndir,调试了我的原始代码,我的原始代码输出是1 4 2 3 5 10,正确的结果应该是1,3,4,2,10,5,我的代码有什么问题?
  • 您使用了sorted(),它不会对列表进行就地排序。您必须将其结果分配给一个变量:students = sorted(students)students.sort()
  • 将您的回复标记为答案。顺便说一句。
【解决方案2】:

解决方案其实还可以,但是对于像这样的小任务,不用声明一个新的类,可以使用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,关键是每对中的第二个项目,即分数。

【讨论】:

  • 谢谢Alex,调试了我的原始代码,我的原始代码输出是1 4 2 3 5 10,正确的结果应该是1,3,4,2,10,5,我的代码有什么问题?
【解决方案3】:

这一行将按分数对分数和 id 进行排序:

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

【讨论】:

  • 感谢Uri,调试了我的原始代码,我的原始代码输出是1 4 2 3 5 10,正确的结果应该是1,3,4,2,10,5,我的代码有什么问题?
猜你喜欢
  • 2019-11-29
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
相关资源
最近更新 更多