你想要做的就是使用冒泡:
def bubble_sort(list_of_students):
"""
Runs the bubble sort algorithm on the student class
@rtype : list
@param list_of_students: List of students to be sorted
@type list_of_students: list
"""
for _ in list_of_students:
for j in xrange(len(list_of_students) - 1):
if list_of_students[j] > list_of_students[j + 1]:
list_of_students[j + 1], list_of_students[j] = list_of_students[j], list_of_students[j + 1]
return list_of_students
尝试以下操作:
from random import randint, choice
import string
class Student(object):
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __gt__(self, other):
if isinstance(other, Student):
return self.name > other.name
raise Exception("Cannot compare Student to Not-A-Student")
def __repr__(self):
return "{name} => {grade}".format(name=self.name, grade=self.grade)
def bubble_sort(list_of_students):
"""
Runs the bubble sort algorithm on the student class
@rtype : list
@param list_of_students: List of numbers to be sorted
@type list_of_students: list
"""
for _ in list_of_students:
for j in xrange(len(list_of_students) - 1):
if list_of_students[j] > list_of_students[j + 1]:
list_of_students[j + 1], list_of_students[j] = list_of_students[j], list_of_students[j + 1]
return list_of_students
l = [Student(choice(string.ascii_uppercase), randint(0, 10)) for i in range(10)]
print bubble_sort(l)
你有没有在所有研究任何排序算法? –
这段代码会导致异常 - 对于最后一个值(讨厌单字母ID)它会抛出异常 – volcano
我知道冒泡排序,选择排序,快速排序和合并排序,但不正确的行是studentList [i] .getName ()= studentList [i + 1] .getName() studentList [i + 1] .getName()= aux – user1012732