链接到对象

2024-04-25 01:41:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我有一个问题:/在函数get longest name中,我想返回人名,但我不想返回,而是一直返回link?这个人的名字。你能帮我说说哪里有问题吗?谢谢:)

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_longest_name(people):
    return (max(people, key=lambda word: (len(word), word)))


people = {}
people['martin'] = Person('Martin', 1991, 'phd')
people['peter'] = Person('Peter', 1995, 'bc')
get_longest_name(people)

我要。。。。->;“马丁”

我应该。。。。->;“马丁”


Tags: ofnameselfgetlongestdefpeopleyear
2条回答

get\u longest\u name函数返回字典中的键,而不是类的属性。下面将解决此问题:

def get_longest_name(people):
    return people[max(people, key=lambda word: (len(word), word))].name

编辑以添加完整的工作答案:

>>> 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 get_longest_name(people):
...     return people[max(people, key=lambda word: (len(word), word))].name
...
>>> people = {}
>>> people['martin'] = Person('Martin', 1991, 'phd')
>>> people['peter'] = Person('Peter', 1995, 'bc')
>>> get_longest_name(people)
Martin

您在迭代键,而不是值。试试这个:

return people[max(people, key=lambda word: (len(word), word))].name

访问people字典中的对象并返回其名称。你知道吗

此外,您还可以访问字典中每个Person对象的名称:

return max(people.values(), key=lambda person: (len(person.name), person.name)).name

相关问题 更多 >