我有一个包含[name, surname, int1, int2]
元素的数组,我需要按以下顺序对其进行排序:
通过int1
(减少)。
如果int1
相同,name
则按“反向”字母顺序排序。
如果name
相同,surname
则按字母顺序排序。
所以我有这个:
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)]
您可以创建一个带有实现的类<
(这<
是CPython所sorted
要求的-如果您正在使用其他Python实现,则可能需要其他比较运算符)。这样就可以完全控制“排序”。例如:
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
为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)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句