我正在尝试按名称进行排序,但它键入错误:typeError:'<'在"人"one_answers"人"的实例之间不支持。你能告诉我问题在哪里吗?这是我的代码。
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()
这就是它所说的:您无法对Person
对象进行排序。如果您想使用此功能,则必须使用您想到的任何类型标准来定义班级的__lt__
操作员 - 也许按名称为字母?
另一种可能性是简单地编写自己的功能,并使用person.mentees.obj_sort
调用。
另外,我不确定为什么这很重要:您从不使用使用此操作的返回值。您将其存储在局部变量a
中(顺便说一句,这是一个差的变量名称),并且永远不会使用它。
如何编写自定义密钥函数并将其传递为sorted()
参数?
sorted_list = sorted(person.mentees, key=lambda p: p.name)