我有一個包含名稱和愛好的類 Person。然后是一個包含人員的串列。
- person1 = Person("MarySmith", ["跳舞", "騎自行車", "烹飪"])
- 人2 = ...
- 人= [人1,人2,..]
我需要回傳按姓名字母順序排序的人員串列,并按字母順序對他們的愛好串列進行排序。
這是我到目前為止所擁有的:
def sort_people_and_hobbies(people: list) -> list:
result = []
for p in people:
result.append(p)
return sorted(result, key=lambda x: x.names)
這是我期望得到的:
print(sort_people_and_hobbies(people)) # -> [KateBrown, MarySmith,..]
print(person1.hobbies) # -> ['biking', 'cooking', 'dancing']
我不知道如何將愛好分類到這個中。無論我做什么,我都會得到一份未分類的愛好串列。
uj5u.com熱心網友回復:
一些愛好可以在課堂上完成,你可以做這樣的方法。
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"])
執行:
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 [5]: p3.hobbies
Out[5]: ['cooking', 'football']
uj5u.com熱心網友回復:
你沒有給出 的實作Person,所以很難給出一個準確的答案。我假設以下。
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)
Person您還可以在創建班級時對 a 的愛好進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/529254.html
標籤:Python列表排序哎呀
