【问题标题】:How to order a list of objects alphabetically?如何按字母顺序排列对象列表?
【发布时间】:2013-11-26 11:33:13
【问题描述】:

如何在不使用任何 python-metods 的情况下按字母顺序对对象列表进行排序? 例如,对于具有属性 Name、Grade 的 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

【问题讨论】:

  • 你研究过排序算法吗?
  • 这段代码会导致异常——对于最后一个 i 值(讨厌单字母 id),它会抛出异常
  • 我知道冒泡排序、选择排序、快速排序和归并排序,但是不正确的行是 studentList[i].getName() = studentList[i+1].getName() studentList[i+ 1].getName() = 辅助
  • @volcano:不,因为范围仅限于len(studentList) - 1
  • @MartijnPieters,没错。 len(studentList) - 1 将给出列表中的最后一个索引

标签: python sorting alphabetical


【解决方案1】:

您正在尝试分配.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]

如果不对排序算法进行更多思考,您的简单循环当然不会产生完整排序。

【讨论】:

  • 这是这个排序算法的主要问题吗?作为评论更好
  • 循环——实际上——是无止境的
  • @AndyT:阻塞 OP 的主要问题是分配问题。缺乏排序算法是下一个障碍。
  • @volcano:while True: 很早就被删除了。
  • 不是排序问题,而是分配问题
【解决方案2】:

你想要做的是使用冒泡排序:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多