I have a class Person that contains names and hobbies. Then there’s a list that contains people.
- person1 = Person(“MarySmith”, [“dancing”, “biking”, “cooking”])
- person2 = …
- people = [person1, person2,..]
I need to return a list of people sorted alphabetically by their name, and also sort their list of hobbies alphabetically.
This is what I have so far:
def sort_people_and_hobbies(people: list) -> list: result = [] for p in people: result.append(p) return sorted(result, key=lambda x: x.names)
This is what I’m expecting to get:
print(sort_people_and_hobbies(people)) # -> [KateBrown, MarySmith,..] print(person1.hobbies) # -> ['biking', 'cooking', 'dancing']
I don’t get how to implement sorting for hobbies into this. No matter what I do I get an unsorted list of hobbies.
Advertisement
Answer
You didn’t give the implementation of Person
, so it’s hard to give an exact answer. I assume the following.
class Person: def __init__(self, name: str, hobbies: list[str]): self.name = name self.hobbies = hobbies def sort_people_and_hobbies(people: list[Person]) -> list[Person]: for person in people: person.hobbies.sort() # we don't have this implementation # so if it's not a dataclass, then modify return sorted(people, key = lambda x: x.name)
You could also sort a Person
‘s hobbies upon class creation.