按照两个不同的属性对数组进行排序/分组
创始人
2024-08-24 12:30:19
0

在Python中,可以使用sorted()函数来对数组进行排序,并通过参数key传入一个自定义的排序函数来按照不同的属性进行排序。下面是一个示例代码:

# 定义一个学生类
class Student:
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

    def __repr__(self):
        return f"Student(name={self.name}, age={self.age}, score={self.score})"

# 创建学生对象列表
students = [
    Student("Alice", 18, 90),
    Student("Bob", 19, 85),
    Student("Charlie", 17, 95),
    Student("David", 20, 80)
]

# 按照年龄升序排序
sorted_by_age = sorted(students, key=lambda student: student.age)
print(sorted_by_age)

# 按照分数降序排序
sorted_by_score = sorted(students, key=lambda student: student.score, reverse=True)
print(sorted_by_score)

输出结果为:

[Student(name=Charlie, age=17, score=95), Student(name=Alice, age=18, score=90), Student(name=Bob, age=19, score=85), Student(name=David, age=20, score=80)]
[Student(name=Charlie, age=17, score=95), Student(name=Alice, age=18, score=90), Student(name=Bob, age=19, score=85), Student(name=David, age=20, score=80)]

这样,我们就可以根据不同的属性对数组进行排序了。如果要分组,可以使用itertools.groupby()函数来实现。

相关内容

热门资讯

透视黑科技!新版边锋掼蛋辅助器... 透视黑科技!新版边锋掼蛋辅助器(wepOKE),太坑了其实真的有挂(有挂介绍)-哔哩哔哩;新版边锋掼...
重大推荐!鄱阳翻精扑克助赢神器... 重大推荐!鄱阳翻精扑克助赢神器购买,德州小辅助app最新版本更新内容,详细有挂(有挂教学)-哔哩哔哩...
分享一款!雀神广东麻将设置方法... 分享一款!雀神广东麻将设置方法(辅助挂)太坑了确实真的有挂(有挂详情)-哔哩哔哩是由北京得雀神广东麻...
十分钟了解(pokernow德... 十分钟了解(pokernow德州)外挂透明挂辅助插件(德州)德州ai机器人(2024已更新)(哔哩哔...
分辨真假!边锋老友二打一有挂(... 分辨真假!边锋老友二打一有挂(wepOke),太坑了竟然真的有挂(有挂透明)-哔哩哔哩;(需添加指定...
透视app!边锋老友棋牌能装挂... 1、透视app!边锋老友棋牌能装挂(wepoKe),太坑了原来真的有挂(有挂详情)-哔哩哔哩;该软件...
发现玩家(Wepoke规律)外... 1、发现玩家(Wepoke规律)外挂透明挂辅助app(智能)透视辅助(2021已更新)(哔哩哔哩);...
每日必备!边锋老友棋牌免费挂,... 1、每日必备!边锋老友棋牌免费挂,hhpoker有挂,详细有挂(有挂总结)-哔哩哔哩;详细教程。2、...
科普攻略!广东雀神智能插件安装... 科普攻略!广东雀神智能插件安装可测试(透视)太坑了竟然真的有挂(有挂方法)-哔哩哔哩;一、广东雀神智...
发现一款(wepoke ai)... wepoke ai高级策略深度解析‌;发现一款(wepoke ai)外挂透明挂辅助工具(线上)发牌规...