[英]How to sort array of string and int values, multiple attributes with alphabetical and “reversed”-alphabetical order
I have an array containing [name, surname, int1, int2]
elements and I need to sort it by this order: 我有一个包含
[name, surname, int1, int2]
元素的数组,我需要按此顺序对其进行排序:
By int1
(decreasing). 通过
int1
(减少)。
If int1
is the same, sort by name
in "reversed"-alphabetical order. 如果
int1
是相同的,排序name
中的“逆转” -alphabetical秩序。
If name
is the same, order by surname
in alphabetical order. 如果
name
相同, surname
字母顺序按surname
排序。
So I have this: 所以我有这个:
print(sorted(a, key = lambda x: [-int(x[2]), x[0], x[1]]))
And I have no idea how to sort x[0]
in reverse-alphabetical order -x[0], x[0][::-1]
doesn't work for me. 我不知道如何排序
x[0]
在反向字母顺序-x[0], x[0][::-1]
不为我工作。
Example: 例:
[('Petia', 'Anja', 3, 0),
('Vasia', 'Katia', 3, 0),
('Petia', 'Katia', 3, 0),
('Kolia', 'Alexey', 10, 0),
('Yana', 'Anja', 10, 0)]
to 至
[('Yana', 'Anja', 10, 0),
('Kolia', 'Alexey', 10, 0),
('Vasia', 'Katia', 3, 0),
('Petia', 'Anja', 3, 0),
('Petia', 'Katia', 3, 0)]
You could create a class with an implementation for <
( <
is all CPythons sorted
requires - if you're using another Python implementation you might need additional comparison operators). 您可以创建一个具有
<
( <
所有CPythons sorted
需求的实现 - 的实现的类 - 如果您使用其他Python实现,则可能需要其他比较运算符)。 That allows full control over the "ordering". 这允许完全控制“排序”。 For example:
例如:
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
Then use that as key
for sorted
: 然后使用它作为
sorted
key
:
>>> 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)]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.