如何对字符串和 int 值数组、按字母顺序和 "reversed"-字母顺序的多个属性进行排序

How to sort array of string and int values, multiple attributes with alphabetical and "reversed"-alphabetical order

我有一个包含 [name, surname, int1, int2] 个元素的数组,我需要按以下顺序对它进行排序:

所以我有这个:

print(sorted(a, key = lambda x: [-int(x[2]), x[0], x[1]]))

而且我不知道如何按逆字母顺序对 x[0] 进行排序 -x[0], x[0][::-1] 对我不起作用。

示例:

[('Petia', 'Anja', 3, 0),
 ('Vasia', 'Katia', 3, 0),
 ('Petia', 'Katia', 3, 0),
 ('Kolia', 'Alexey', 10, 0),
 ('Yana', 'Anja', 10, 0)]

[('Yana', 'Anja', 10, 0),
 ('Kolia', 'Alexey', 10, 0),
 ('Vasia', 'Katia', 3, 0),
 ('Petia', 'Anja', 3, 0),
 ('Petia', 'Katia', 3, 0)]

您可以创建一个 class 实现 << 是 CPythons sorted 所需要的 - 如果您正在使用另一个 Python 实现,您可能需要额外的比较运算符)。这允许完全控制 "ordering"。例如:

class Sorter(object):
    def __init__(self, tup):
        self.name, self.surname, self.int1, self.int2 = tup
    def __lt__(self, other):
        # Just to make the logic clearer, in practise you could do nest the ifs
        # to avoid computing self.int1 == other.int1 twice
        if self.int1 == other.int1 and self.name == other.name:
            return self.surname < other.surname
        elif self.int1 == other.int1:
            return self.name > other.name
        else:
            return self.int1 > other.int1

然后将其用作 key for sorted:

>>> sorted(a, key=Sorter)
[('Yana', 'Anja', 10, 0),
 ('Kolia', 'Alexey', 10, 0),
 ('Vasia', 'Katia', 3, 0),
 ('Petia', 'Anja', 3, 0),
 ('Petia', 'Katia', 3, 0)]
>>> intab='abcdefghijklmnopqrstuvwxyz'
>>> tab = string.maketrans(intab+intab.upper(), intab[::-1]+intab.upper()[::-1])
>>> 
>>> slst = sorted(lst, key = lambda x: [-int(x[2]), x[0].translate(tab), x[1]])
>>> pprint(slst)
[('Yana', 'Anja', 10, 0),
 ('Kolia', 'Alexey', 10, 0),
 ('Vasia', 'Katia', 3, 0),
 ('Petia', 'Anja', 3, 0),
 ('Petia', 'Katia', 3, 0)]
>>>