python 通过函数方式按多个键排序

问题描述 投票:0回答:2

首先,我为我的英语不好而道歉。

这是我的问题。

有一些清单

lists = [('Bill', 1), ('Carol', 2), ('Abel', 3), ('Zekeq', 2), ('Zekea', 2), ('Carol', 2), ('Al', 2), ('Chris', 3)]

我想按多个键排序。

第一、第二个整数值按升序排序

然后,第一个字符串值按降序排序

在Python中,像这样的多键排序

sorted(lists, key=lambda e: (e[1], -e[0])

但你知道,

-e[0]
不是工作。因为
minus
无法使用字符串值。

我搜索了一下,他们说使用

ord
函数,或
sorted(sorted())

但实际上两者都不起作用。

first、

ord
函数仅适用于第一个字符。但我想按完整字符串排序。

第二,排序两次,第二次排序会破坏第一次排序的结果。

我想要这样的

sort().thenSortDesc()

我考虑

locale.strcoll
来比较字符串。

sorted(lists, key=cmp_to_key(lambda x, y: (x[1] - y[1], -locale.strcoll(x[0], y[0]))))

但这不起作用! (我不知道为什么)而且真的很难读。

最后,我写了这样的函数(不完全有效,它只是伪的)

def compare(x, y):
    if x[1] < y[1]:
        return 1
    elif x[1] > y[1]:
        return -1
    if x[0] > y[0]:
        return 1
    elif x[0] < y[0]:
        return -1
    return 0

sorted(list, key=cmp_to_key(compare))

效果很好。但这真的是非常脏的代码。

在 kotlin 中,它的工作原理就像这样

list.sorted().thenSortedDesc()

Python 中还有其他干净的方法吗?

对于函数式编程来说,这真的是一种很好的语言吗?

python
2个回答
0
投票

这个怎么样:

sorted(lists, key=lambda e: (-e[1], e[0]), reverse=True)

0
投票

我不确定人们会认为这是任何“清洁剂”,但这是另一种方法:

sorted(lists, key=lambda e: (-e[1], e[0]), reverse=True)
© www.soinside.com 2019 - 2024. All rights reserved.