简体   繁体   中英

How to order a list of objects alphabetically?

How can I sort a list of objects alphabetically without using any python-metods? For instance for a class Student with attributes Name, Grade I tried writing the following code, but it doesn't work:

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

You are trying to assign to the result of the .getName() call, which is not going to work all too well. Use studentList[i] and studentList[i + 1] directly ; you only need the .getName() call results to compare the student names:

aux = studentList[i]
studentList[i] = studentList[i+1]
studentList[i+1] = aux

To swap two items in your list, just use multiple assignment (no need for an extra temporary variable):

studentList[i], studentList[i+1] = studentList[i+1], studentList[i]

Without some more thought into the sorting algorithm, your simple loop will not, of course, result in a full sort.

What you're trying to do is use 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

Try the following:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM