简体   繁体   中英

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:

  • By int1 (decreasing).

  • If int1 is the same, sort by name in "reversed"-alphabetical order.

  • If name is the same, order by surname in alphabetical order.

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.

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). 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(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)]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM