以下代码打印学生编号和学生分数。
def main():
answers = [
['A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
['D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'],
['E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'],
['C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'],
['A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
['B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
['B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
['E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D']]
keys = ['D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D']
for i in range(len(answers)):
correctCount = 0
for j in range(len(answers[i])):
if answers[i][j] == keys[j]:
correctCount += 1
results = [i,correctCount]
print(results, end = "") # this line used to be - print("Student", i, "'s correct count is", correctCount)
main()
我的目标是将学生分数从最低到最高排序,而不会混淆与该分数相关联的学号。我试图以这些形式使用sort函数:
results1 = sorted(results, key = lambda x: x[1])
results.sort(key = itemgetter(1))
results.sort()
使用所有这三个尝试我仍然无法使其工作。有任何想法吗?
预期产出:
[3, 4]
[2, 5]
[1, 6]
[0, 7]
[5, 7]
[6, 7]
[7, 7]
[4, 8]
第一列是学生#,第二列是分数。
答案 0 :(得分:1)
您没有构建results
,results = [i, correctCount]
的列表,只需覆盖结果,您需要:
results = []
for i in range(len(answers)):
correctCount = 0
for j in range(len(answers[i])):
if answers[i][j] == keys[j]:
correctCount += 1
results.append([i, correctCount])
results = sorted(results, key=lambda x: x[1])
然后您的排序代码应该有效。
然而,python中更惯用的是迭代实际列表而不是range(len(list))
,这通常可以简化代码,上面的内容可以重写:
results = []
for student, student_answers in enumerate(answers):
correctCount = 0
for answer, key in zip(student_answers, keys):
if answer == key:
correctCount += 1
results.append([student, correctCount])
results = sorted(results, key=lambda x: x[1])
哪个比原始代码更具可读性 您还可以使用理解和生成器来减少它:
results = []
for student, student_answers in enumerate(answers):
results.append([student, sum(ans == key for ans, key in zip(student_answers, keys)])
results = sorted(results, key=lambda x: x[1])
如果你真的想走这么远,你可以一气呵成:
results = sorted(((student, sum(a == k for a, k in zip(ans, keys)))
for student, ans in enumerate(answers)), key=lambda x: x[1])
# [(3, 4), (2, 5), (1, 6), (0, 7), (5, 7), (6, 7), (7, 7), (4, 8)]