首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何按字母顺序排列对象列表?

如何按字母顺序排列对象列表?
EN

Stack Overflow用户
提问于 2013-11-26 11:33:13
回答 2查看 1.1K关注 0票数 0

如何在不使用python的情况下按字母顺序排序对象列表?例如,对于一个具有属性名称的类,I年级试着编写以下代码,但它不起作用:

代码语言:javascript
代码运行次数:0
运行
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-26 11:35:45

您正在尝试将.getName()调用的结果分配给它,它不会很好地工作。直接使用studentList[i]studentList[i + 1];您只需要使用.getName()调用结果来比较学生的名字:

代码语言:javascript
代码运行次数:0
运行
复制
aux = studentList[i]
studentList[i] = studentList[i+1]
studentList[i+1] = aux

要交换列表中的两个项,只需使用多个赋值(不需要额外的临时变量):

代码语言:javascript
代码运行次数:0
运行
复制
studentList[i], studentList[i+1] = studentList[i+1], studentList[i]

如果不考虑排序算法,那么简单的循环当然不会导致完整的排序。

票数 3
EN

Stack Overflow用户

发布于 2013-11-26 11:49:10

你想要做的是使用bubblesort:

代码语言:javascript
代码运行次数: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

尝试以下几点:

代码语言:javascript
代码运行次数:0
运行
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20215945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档