2013-11-26 107 views
0

如何在不使用任何python-metods的情况下按字母顺序排列对象列表? 例如,对于一类学生与属性名称,牌号我试着写了下面的代码,但它不工作:如何按字母顺序排列对象列表?

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

你有没有在所有研究任何排序算法? –

+0

这段代码会导致异常 - 对于最后一个值(讨厌单字母ID)它会抛出异常 – volcano

+0

我知道冒泡排序,选择排序,快速排序和合并排序,但不正确的行是studentList [i] .getName ()= studentList [i + 1] .getName() studentList [i + 1] .getName()= aux – user1012732

回答

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] 

无对排序算法有更多想法,当然,您的简单循环不会导致完全排序。

+0

这是排序算法的主要问题吗?这是更好的评论 –

+0

循环 - 它是 - 是无止境的 – volcano

+0

@AndyT:阻塞OP的主要问题是分配问题。排序算法的缺乏是下一个障碍。 –

0

你想要做的就是使用冒泡:

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)