我似乎无法弄清楚如何按学生ID对学生列表进行排序。我有一个字符串列表,每个字符串都包含学生的姓名和ID。它看起来像这样:
student_list = ["John,4", "Jake,1", "Alex,10"]
我希望输出看起来像这样:
["Jake,1", "John,4", "Alex,10"]
我的代码如下所示:
def sort_students_by_id(student_list):
for string in student_list:
comma = string.find(",")+1
student = [(string[comma:])]
for index in range(len(student)):
minpos = index
for pos in range(index+1, len(student)):
if student[pos] < student[minpos]:
minpos = pos
tmp = student[index]
student[index] = student[minpos]
student[minpos] = tmp
return student_list
print(sort_students_by_id(student_list))
答案 0 :(得分:2)
你可以这样做:
def sort_students_by_id(student_list):
return sorted(student_list, key=lambda s: int(s.split(',')[-1]))
# ['Jake,1', 'John,4', 'Alex,10']
print(sort_students_by_id(student_list))