如何在不使用任何python-metod的情况下按字母顺序对对象列表进行排序? 例如,对于具有属性Name的类Student,我尝试编写以下代码,但它不起作用:
for i in range (0, len(studentList)-1):
if studentList[i].getName() > studentList[i+1].getName():
aux = studentList[i].getName()
studentList[i].getName() = studentList[i+1].getName()
studentList[i+1].getName() = aux
答案 0 :(得分:3)
您正在尝试分配.getName()
来电的结果,这不会太好用。直接使用studentList[i]
和studentList[i + 1]
;您只需要.getName()
通话结果来比较学生姓名:
aux = studentList[i]
studentList[i] = studentList[i+1]
studentList[i+1] = aux
要交换列表中的两个项目,只需使用多个赋值(不需要额外的临时变量):
studentList[i], studentList[i+1] = studentList[i+1], studentList[i]
如果不考虑排序算法,那么简单的循环当然不会产生完整的排序。
答案 1 :(得分:0)
您要做的是使用bubblesort:
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)