【发布时间】:2026-01-12 13:50:01
【问题描述】:
我有 3 组学生成绩:group_a、group_b 和 group_c
每个组都包含一个按以下顺序排列的元组列表:(student_number,score)。
我想根据每个学生的分数打印一条消息:
- A 组中的每个学生:“做得好学生{}。你的分数是 {}”
- B 组中的每个学生:“干得好学生{}。你的分数是 {}”
- C 组中的每个学生:“嗨,学生{}。你的分数是 {}。你可以做得更好。”
为了实现这一点,我在按元组的第一个元素对它们进行排序之前组合了所有 3 个组。
all_groups = group_a + group_b + group_c
# take first element for sort
def takeFirst(elem):
return elem[0]
#using the 'takeFirst' function, sort tuple based on the first element
all_groups.sort(key=takeFirst)
#each tuple reflects (student number, score)
print(all_groups)
[(1, 29), (2, 54), (3, 52), (4, 50), (5, 30), (6, 57), (7, 56), (8, 47), (9, 51), (10, 55)]
接下来,我根据每个学生的分数打印了一条消息。
collection4 = []
collection5 = []
collection6 = []
for number, pair1 in enumerate(all_groups):
# Unpack pair1: number, student_score
student_number, score1 = pair1
# print msg for each student. Attach every sentence into a 'collection' bucket.
if score1 >=60:
collection4.append('Well done student {}. Your score was {}.'.format(student_number, score1))
elif score1 >=50 and score1<=59:
collection5.append('Good work student {}. Your score was {}.'.format(student_number, score1))
else:
collection6.append('Hi student {}. Your score was {}. You can do better than this.'.format(student_number, score1))
接下来,我将集合 4、5 和 6 合并到一个桶中。
totalcollection = collection4 + collection5 + collection6
但是,当我打印 'totalcollection' 变量的内容时,结果不是按学号升序排列的。
我可以知道如何解决这个问题吗?谢谢。
【问题讨论】:
标签: python function if-statement tuples