我正在尝试按名称排序但是输入错误:TypeError:'<' “人”和“人”的实例之间不支持。你能告诉我问题出在哪里吗?这是我的代码。
class Person:
def __init__(self, name, year_of_birth, degree):
self.name = name
self.year_of_birth = year_of_birth
self.degree = degree
self.mentor = None
self.mentees = []
def create_mentorship(mentor, mentee):
mentee.mentor = mentor
mentor.mentees.append(mentee)
def get_founder(people):
for person in people:
if people[person].mentor == None:
return people[person]
def print_mentorship_tree(people):
person = get_founder(people)
print_mentorship_subtree(person)
def print_mentorship_subtree(person, level=0):
a = []
print((" " * level) + person.name +' (' + str(person.year_of_birth) + ')')
for mentee in person.mentees:
print_mentorship_subtree(mentee, level + 1)
a = sorted(person.mentees)
>>> people = {}
>>> people['Martin'] = Person('Martin', 1991, 'phd')
>>> people['Lukas'] = Person('Lukas', 1991, 'phd')
>>> people['Tom'] = Person('Tom', 1993, 'mgr')
>>> people['Honza'] = Person('Honza', 1995, 'bc')
>>> create_mentorship(people['Martin'], people['Tom'])
>>> create_mentorship(people['Tom'], people['Honza'])
>>> create_mentorship(people['Martin'], people['Lukas'])
>>> print_mentorship_tree(people)
错误:
Traceback (most recent call last):
File "so.py", line 38, in <module>
print_mentorship_tree(people)
File "so.py", line 20, in print_mentorship_tree
print_mentorship_subtree(person)
File "so.py", line 28, in print_mentorship_subtree
a = sorted(person.mentees)
TypeError: unorderable types: Person() < Person()
答案 0 :(得分:3)
它就是它所说的:你无法对Person
个对象进行排序。如果你希望这个工作,你必须至少为你的班级定义__lt__
运算符,使用你想到的任何排序标准 - 可能按名称按字母顺序排列?
另一种可能性是简单地编写自己的函数,并使用person.mentees.obj_sort
调用它。
另外,我不确定为什么这很重要:你永远不会使用这个操作的返回值。你将它存储在局部变量a
中(顺便说一下,这是一个糟糕的变量名),从不使用它。
答案 1 :(得分:3)
如何编写自定义key函数并将其作为sorted()
参数传递?
sorted_list = sorted(person.mentees, key=lambda p: p.name)