按照多个条件对集合进行排序
创始人
2024-08-23 20:00:16
0

可以使用Python的sorted()函数来对集合进行排序。sorted()函数可以接受一个可迭代对象并返回一个已排序的列表。在使用sorted()函数时,我们可以使用lambda表达式来指定多个排序条件。

以下是一个例子,假设我们要对以下学生集合按照分数从高到低、若分数相同则按照年龄从小到大排序:

students = [ {'name': 'Amy', 'score': 90, 'age': 20}, {'name': 'Bob', 'score': 80, 'age': 25}, {'name': 'Carl', 'score': 90, 'age': 21}, {'name': 'Dave', 'score': 70, 'age': 23}, {'name': 'Eve', 'score': 80, 'age': 22} ]

我们可以使用以下代码:

sorted_students = sorted(students, key=lambda student: (-student['score'], student['age']))

在lambda表达式中,我们首先对分数取负数,这是因为sorted()函数默认按照升序排序,我们要倒序排列。在分数相同的情况下,我们按照年龄从小到大排序,因此我们将年龄作为第二个排序条件。

最终得到的sorted_students列表如下所示:

[ {'name': 'Carl', 'score': 90, 'age': 21}, {'name': 'Amy', 'score': 90, 'age': 20}, {'name': 'Bob', 'score': 80, 'age': 25}, {'name': 'Eve', 'score': 80, 'age': 22}, {'name': 'Dave', 'score': 70, 'age': 23} ]

可以看到,按照我们的要求,集合中的元素已经按照多个条件进行了排序。

相关内容

热门资讯

透视代打!aapoker插件下... 透视代打!aapoker插件下载(透视)aapoker破解侠是真的吗,微扑克教程(有挂技巧)1、很好...
透视美元局!wepoker透视... 透视美元局!wepoker透视脚本视频,wepoker代打辅助机器人(详细黑侠辅助器正版下载);1、...
透视代打!poker辅助器免费... 透视代打!poker辅助器免费安装,wepoker破解工具(详细黑侠辅助器正版下载)1、poker辅...
透视透视!aapoker安装包... 透视透视!aapoker安装包怎么使用(透视)aapoker公共底牌,可靠技巧(有挂辅助)一、aap...
透视玄学!aapoker辅助器... 透视玄学!aapoker辅助器是真的吗(透视)aapoker辅助软件合法吗,玩家教你(有挂解密);1...
辅助透视!wepoker买脚本... 辅助透视!wepoker买脚本靠谱吗,wepoker免费脚本咨询(详细有透视方法)1、进入到wepo...
透视存在!wepoker正确养... 透视存在!wepoker正确养号方法,wepoker究竟有没有透视(详细数据分析)一、wepoker...
透视系统!aapoker透视脚... 透视系统!aapoker透视脚本(透视)aapoker脚本怎么用,必赢教程(有挂教程)1、构建自己的...
透视有挂!wepoker手机插... 透视有挂!wepoker手机插件,wepoker免费脚本咨询(详细-h5下载);一、wepoker免...
透视黑科技!aapoker怎么... 透视黑科技!aapoker怎么设置提高好牌几率(透视)aapoker ai插件,曝光教程(有挂解说)...