如何在Python中对列表内的数字子列表进行冒泡排序?
修改冒泡排序实现成绩子列表内部排序
原始学生与成绩数据:
students = ['tom', 'richard', 'henry'] grades = [[78, 88, 98], [88, 76, 55], [80, 81, 79]]
需求是对每个学生的成绩子列表内部从高到低排序后,对应输出学生和成绩。但当前的bubbleSort函数仅对成绩列表的子列表整体排序,输出结果不符合要求:
tom [78, 88, 98] richard [80, 81, 79] henry [88, 76, 55]
当前使用的bubbleSort函数代码:
def bubbleSort(scores): maxLength = len(scores) - 1 while maxLength >= 0: index = 0 while index <= maxLength - 1: if scores[index] > scores[index + 1]: temp = scores[index] scores[index] = scores[index + 1] scores[index + 1] = temp index = index + 1 maxLength = maxLength - 1 return scores
修改方案
要实现需求,需要做两处调整:
- 调整冒泡排序的判断条件,让子列表内部按从高到低排序(原代码是从小到大排序);
- 遍历成绩列表中的每个子列表,对单个子列表调用排序函数,而非直接对整个成绩列表排序。
修改后的完整代码:
def bubbleSort(scores): maxLength = len(scores) - 1 while maxLength >= 0: index = 0 while index <= maxLength - 1: # 前一个元素小于后一个则交换,实现降序排序 if scores[index] < scores[index + 1]: temp = scores[index] scores[index] = scores[index + 1] scores[index + 1] = temp index = index + 1 maxLength = maxLength - 1 return scores students = ['tom', 'richard', 'henry'] grades = [[78, 88, 98], [88, 76, 55], [80, 81, 79]] # 对每个成绩子列表单独排序 sorted_grades = [bubbleSort(grade) for grade in grades] # 对应输出学生和排序后的成绩 for student, grade in zip(students, sorted_grades): print(f"{student} {grade}")
执行后输出结果:
tom [98, 88, 78] richard [88, 76, 55] henry [81, 80, 79]
内容的提问来源于stack exchange,提问作者Luis Lopez
相关产品推荐
相关产品推荐

