栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python | sort按照多个原则排序

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python | sort按照多个原则排序

题目: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 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022114.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号