我创建)与属性名和姓命名的学生(类。在I类创建的类变量 - > all_students = []如何通过这些对象的属性的排序LEN对象的名单? - Python的
在创建对象时,它被添加到类变量= all_students。
如何通过属性名称的排序lenght对象的该列表从最长到最短?
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)
我试着用操作符,但我不能这样做。将gratefull帮助。
OP希望它是反向排序,所以你需要'-LEN(s.name)'。 –
...或“reverse = True”。 – SethMMorton