Home > front end >  Sort one inside another
Sort one inside another

Time:11-05

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.

CodePudding user response:

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.

CodePudding user response:

Sort of hobbies can be done in the class itself, You can do an approach like this.

class Person:
    def __init__(self, name, hobbies):
        self.name = name
        self.hobbies = sorted(hobbies)

def sort_people(people: list) -> list:
    name_list = [p.name for p in people]
    return sorted(name_list)

p1 = Person("MarySmith", ["dancing", "biking", "cooking"])
p2 = Person("John", ["dancing", "reading"])
p3 = Person("KateBrown", ["football", "cooking"])

Execution:

In [1]: p1.hobbies
Out[1]: ['biking', 'cooking', 'dancing']

In [2]: people = [p1, p2, p3]

In [2]: sort_people(people)
Out[2]: ['John', 'KateBrown', 'MarySmith']

In [3]: p1.hobbies
Out[3]: ['biking', 'cooking', 'dancing']

In [4]: p2.hobbies
Out[4]: ['dancing', 'reading']

In [41]: p3.hobbies
Out[41]: ['cooking', 'football']
  • Related