doctopus
doctopus

Reputation: 5657

How do I sort this list of tuples by both values?

I have a list of tuples: [(2, Operation.SUBSTITUTED), (1, Operation.DELETED), (2, Operation.INSERTED)]

I would like to sort this list in 2 ways:

First by its 1st value by ascending value, i.e. 1, 2, 3... etc Second by its 2nd value by reverse alphabetical order, i.e. Operation.SUBSTITITUTED, Operation.INSERTED, Operation, DELETED

So the above list should be sorted as:

[(1, Operation.DELETED), (2, Operation.SUBSTITUTED), (2, Operation.INSERTED)]

How do I go about sort this list?

Upvotes: 3

Views: 1526

Answers (4)

Jean-François Fabre
Jean-François Fabre

Reputation: 140246

In this particular case, because the order of comparison can be easily inverted for integers, you can sort in one time using negative value for integer key & reverse:

lst = [(2, 'Operation.SUBSTITUTED'), (1, 'Operation.DELETED'), (2, 'Operation.INSERTED')]
res = sorted(lst, key=lambda x: (-x[0],x[1]), reverse=True)

result:

[(1, 'Operation.DELETED'), (2, 'Operation.SUBSTITUTED'), (2, 'Operation.INSERTED')]

negating the integer key cancels the "reverse" aspect, only kept for the second string criterion.

Upvotes: 2

Austin
Austin

Reputation: 26039

Another way using itemgetter from operator module:

from operator import itemgetter

lst = [(2, 'Operation.SUBSTITUTED'), (1, 'Operation.DELETED'), (2, 'Operation.INSERTED')]

inter = sorted(lst, key=itemgetter(1), reverse=True)
sorted_lst = sorted(inter, key=itemgetter(0))

print(sorted_lst)

# [(1, 'Operation.DELETED'), (2, 'Operation.SUBSTITUTED'), (2, 'Operation.INSERTED')]                                

Upvotes: 0

Abhishek Keshri
Abhishek Keshri

Reputation: 3244

You can use this:

from operator import itemgetter
d = [(1, 'DELETED'), (2, 'INSERTED'), (2, 'SUBSTITUTED')]
d.sort(key=itemgetter(1),reverse=True)
d.sort(key=itemgetter(0))
print(d)

Upvotes: 0

jpp
jpp

Reputation: 164753

Since sorting is guaranteed to be stable, you can do this in 2 steps:

lst = [(2, 'Operation.SUBSTITUTED'), (1, 'Operation.DELETED'), (2, 'Operation.INSERTED')]

res_int = sorted(lst, key=lambda x: x[1], reverse=True)
res = sorted(res_int, key=lambda x: x[0])

print(res)

# [(1, 'Operation.DELETED'), (2, 'Operation.SUBSTITUTED'), (2, 'Operation.INSERTED')]

Upvotes: 4

Related Questions