根据多个谓词对字符串列表进行排序 [英] Sort a list of strings based on multiple predicates

查看:99
本文介绍了根据多个谓词对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个字符串列表:

['foo2', 'abacus', 'azz', 'foo', 'foo3', 'bar', 'azb', 'bars13']

这是调用sorted后的普通排序版本的样子:

This is how the normal sorted version looks like after calling sorted:

['abacus', 'azb', 'azz', 'bar', 'bars13', 'foo', 'foo2', 'foo3']

我想先对它们进行排序,然后对所有具有相同首字母的字符串按降序排序.

I want to first order them all, and then, for all strings with the same first letter, sort in descending order.

对于上面的示例,我想要

For the example above, I want

['azz', 'azb', 'abacus', 'bars13', 'bar', 'foo3', 'foo2', 'foo']

我该怎么做?

推荐答案

您可以先按降序排序,然后再按首字母排序.由于Python的排序算法是稳定的,因此这将导致第二种排序中的所有联系"(即具有相同第一个字母的单词)保持与第一种排序相同的相对顺序.

You could first sort in descending order, then sort by first letter. Since Python's sorting algorithm is stable, this will result in all "ties" in the second sort (i.e. words with the same first letter) remaining in the same relative order as the first sort.

l = sorted(l, reverse=True)
l = sorted(l, key=lambda s: s[0])

您也可以在一次调用sorted()的情况下执行此操作,如下所示:

You could also do this in one call to sorted() as follows:

l = sorted(l, key=lambda s: (-ord(s[0]), s), reverse=True)

这篇关于根据多个谓词对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆