2

Let's say I have this list of tuples:

[(30, 'B'), (50, 'B'), (40, 'C'), (10, 'A'), (80, 'A'), (5, 'A')]

I need to sort the tuples by their second element in descending order but with the condition that all of the tuples with an identical second element are next to one another.

So, it should look like

[(80, 'A'), (10, 'A'), (5, 'A'), (50, 'B'), (30, 'B'), (40, 'C')]

How can I do this?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Anton
  • 29
  • 2

2 Answers2

5

You want to sort by the second element, then the negative of the first:

>>> values = [(30, 'B'), (50, 'B'), (40, 'C'), (10, 'A'), (80, 'A'), (5, 'A')]

>>> sorted(values, key=lambda value: (value[1], -value[0]))
[(80, 'A'), (10, 'A'), (5, 'A'), (50, 'B'), (30, 'B'), (40, 'C')]

The key argument to sorted needs to be a function which converts each value into the value you want to compare.

I pass in a lambda function which takes the value (a tuple, e.g. (40, 'C')), and then returns ('C', -40). Python then compares the first reversed value, 'C', and if it matches, compares the second value -40.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
3

Use lambda for such needs:

a = [(30, 'B'), (50, 'B'), (40, 'C'), (10, 'A'), (80, 'A'), (5, 'A')]
a.sort(key=lambda x: (x[1], -x[0]))
print(a)

Output:

[(80, 'A'), (10, 'A'), (5, 'A'), (50, 'B'), (30, 'B'), (40, 'C')]
Digital Farmer
  • 1,705
  • 5
  • 17
  • 67