2013-11-26 134 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)