题目:Please write a function named which returns a new list of routes, sorted by difficulty, i.e. grade, from hardest to easiest. For routes with the same grade, the longer one is more difficult. The scale of climbing route grades is 4, 4+, 5, 5+, 6A, 6A+, ..., which in practice works out as the alphabetical order for strings.sort_by_difficulty(routes: list)
意思就是,把这些爬山对象按照难度排序(难的在前),并且如果难度一致,则按照长度排序。
class ClimbingRoute:
def __init__(self, name: str, length: int, grade: str):
self.name = name
self.length = length
self.grade = grade
def __str__(self):
return f"{self.name}, length {self.length} metres, grade {self.grade}"
def sort_by_length(routes: list):
def length(item):
return item.length
return sorted(routes, key = length, reverse=True)
def sort_by_difficulty(routes: list):
def difficulty(item):
return item.grade
return sorted(routes, key =lambda x:(x.grade, x.length), reverse=True)
最后一句:return sorted(routes, key =lambda x:(x.grade, x.length), reverse=True),x是任意命名的,代表数组中的对象。 x:(x.grade, x.length)则是在按照grade排序的基础上,再按照length排序。最后逆序。
补充:官方题解
def sort_by_difficulty(routes: list):
def difficulty_order(route):
return (route.grade, route.length) # 因为默认排序是按照第一个排序,再按照第二位排序
return sorted(routes, key=difficulty_order, reverse=True)
题源:Helsinki,part 12



