1

Firstly I created a class like this

class Student:
    def __init__(self, name, grade, age):
            self.name = name
            self.grade = grade

Then I have a list of Student object

L = [(Student: Tim, 99), (Student: Alice, 99), (Student: Bob, 88)]

How can i sort this list in descending order of score, and then if two have the same score, sort them by name in ascending alphabetic order

I have tried to use attrgetter, but i always get the same list like the above L

The expected output is

L = [ (Student: Alice, 99),(Student: Tim, 99), (Student: Bob, 88)]

Peter Wen
  • 21
  • 6

3 Answers3

0

You can add key arg in sorted method

sortedL = sorted(L, key=lambda student: student.name)
thangtn
  • 856
  • 6
  • 7
0

Define a function that can be used as the key argument to sort. You get to define the function so you can specify how it sorts

>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] 

https://wiki.python.org/moin/HowTo/Sorting

bravosierra99
  • 1,331
  • 11
  • 23
0

By default sorted uses the __cmp__ method of the objects that you're comparing.

class Student(object):

    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age

    def __cmp__(self, other):
        if self.grade < other.grade:
            return +1
        elif self.grade > other.grade:
            return -1
        else:
            return cmp(self.name, other.name)

    def __repr__(self):
        return "({}, {})".format(self.name, self.grade)

s1 = Student('Tim', 99, 12)
s2 = Student('Alice', 99, 12)
s3 = Student('Bob', 88, 13)

sorted([s1, s2, s3])
Batman
  • 8,571
  • 7
  • 41
  • 80
  • `__cmp__` (and `cmp`) is deprecated and unnecessary anyway. Py3 uses `__lt__` exclusively, and Py2 will happily use `__lt__`, and only needing to test `__lt__` is typically faster. Beyond that, implementing the comparison on the class implies it is the natural ordering of Students in general, when I highly doubt most people would consider the abstract concept of a student to order primarily by grade. It's much better, and faster (because it avoids `n log n` invocations of slow user defined functions), to use the `key` argument of `list.sort`/`sorted` (which is only invoked `n` times). – ShadowRanger Nov 03 '16 at 03:09