2017-07-16 36 views
-1

我创建)与属性名和姓命名的学生(类。在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帮助。

回答

4

你快到了。你只需要改变你的键位使用lambda

sorted(Student.all_students, key=lambda x: -len(x.name)) 

这会递减名的长度进行排序您的学生名单(注意-len(...)

如果你想使用attrgetter,你需要你的密钥更改为key=lambda x: -len(operator.attrgetter('name')(x)),但在这一点上,它变得更简单,只需使用x.name


这里有一个演示。我已经添加了一个__repr__方法,以便它变得更清晰。

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)] 
1

你不能用attrgetter做到这一点。使用拉姆达:

sorted(Student.all_students, key=lambda s: len(s.name)) 
+0

OP希望它是反向排序,所以你需要'-LEN(s.name)'。 –

+1

...或“reverse = True”。 – SethMMorton

0

我没有足够的声誉尚未就此发表评论:

COLDSPEED的解决方案是好的,但更Python仍然使用一键功能(不拉姆达),并使用反向ARG

def name_length(student): 
    return len(student.name) 


sorted(Student.all_students, key=name_length, reverse=True) 
相关问题