Reputation: 423
I created class named Student() with attributes name and surname. In that class I created class variable -> all_students = []
When creating an object, it is being added to that class variable = all_students.
How to sort that list of objects by the lenght of the attribute name from longest to shortest?
import operator
class Student:
all_students = []
def __init__(self, name, surname):
self.name = name
self.surname = surname
Student.all_students.append(self)
s_1 = Student("Jacobbbb", "anything")
s_2 = Student("Mat", "anything1")
s_3 = Student("Marcooooooo", "sss")
new_list = sorted(Student.all_students, key=operator.attrgetter(len('name')))
for student in new_list:
print(student.name)
I tried with operator, but I can't do that in this way. Will be gratefull for help.
Upvotes: 0
Views: 3391
Reputation: 396
I haven't enough reputation to comment yet:
COLDSPEED's solution is good, but more pythonic still to use a key function (not lambda), and use the reverse arg
def name_length(student):
return len(student.name)
sorted(Student.all_students, key=name_length, reverse=True)
Upvotes: 2
Reputation: 402423
You're almost there. You just need to change your key a bit to use a lambda
:
sorted(Student.all_students, key=lambda x: -len(x.name))
This'll sort your student list in descending order of name length (notice the -len(...)
.
If you wanted to use attrgetter
, you'd need to change your key to key=lambda x: -len(operator.attrgetter('name')(x))
. But at that point, it becomes simpler to just use x.name
.
Here's a demonstration. I've added a __repr__
method so it becomes clearer.
In [320]: def __repr__(self): return 'Student(%s %s)' %(self.name, self.surname)
In [321]: Student.__repr__ = __repr__
In [322]: sorted(Student.all_students, key=lambda x: -len(x.name))
Out[322]: [Student(Marcooooooo sss), Student(Jacobbbb anything), Student(Mat anything1)]
Upvotes: 6
Reputation: 599580
You can't do it with attrgetter
. Use a lambda:
sorted(Student.all_students, key=lambda s: len(s.name))
Upvotes: 0