sort tuple with multiple condition

Viewed 131

I'm trying to sort a list of tuple with 3 elements in decreasing order based on the third elements.

Input:

 [('a', 1, 50),('b', 2, 50),('c', 3, 25),('d',4,20),('e',5,14)]

My output:

[('b', 2, 50),('a', 1, 50),('c', 3, 25), ('d',4,20),('e',5,14)]

Expected output:

[('a', 1, 50),('b', 2, 50),('c', 3, 25), ('d', 4, 20),('e', 5, 14)]

I want to place additional condition when the 3rd element in the tuple are even, the tuple with smaller 2nd element will be place in front.

Thanks !

1 Answers

Use sorted with two keys and reverse:

sorted(tuples, key=lambda x: (x[2], -x[1]), reverse=True)

Output:

[('a', 1, 50), ('b', 2, 50), ('c', 3, 25), ('d', 4, 20), ('e', 5, 14)]
Related