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:
JavaScript
x
6
1
def sort_people_and_hobbies(people: list) -> list:
2
result = []
3
for p in people:
4
result.append(p)
5
return sorted(result, key=lambda x: x.names)
6
This is what I’m expecting to get:
JavaScript
1
3
1
print(sort_people_and_hobbies(people)) # -> [KateBrown, MarySmith,..]
2
print(person1.hobbies) # -> ['biking', 'cooking', 'dancing']
3
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.
JavaScript
1
11
11
1
class Person:
2
def __init__(self, name: str, hobbies: list[str]):
3
self.name = name
4
self.hobbies = hobbies
5
6
def sort_people_and_hobbies(people: list[Person]) -> list[Person]:
7
for person in people:
8
person.hobbies.sort() # we don't have this implementation
9
# so if it's not a dataclass, then modify
10
return sorted(people, key = lambda x: x.name)
11
You could also sort a Person
‘s hobbies upon class creation.