如何在不使用python的情况下按字母顺序排序对象列表?例如,对于一个具有属性名称的类,I年级试着编写以下代码,但它不起作用:
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
发布于 2013-11-26 03:35:45
您正在尝试将.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]
如果不考虑排序算法,那么简单的循环当然不会导致完整的排序。
发布于 2013-11-26 03:49:10
你想要做的是使用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)
https://stackoverflow.com/questions/20215945
复制