0

I have a list that looks like this: my_list = [('a', 4), ('z', 3), ('y', 3), ('x', 3), ('p', 2), ('o', 2)].

It is important that the tuples in the list are sorted by the second element ([1]) in the descending order.

Now I need to sort each group of tuples with the same second element in the ascending order based on the first element ([0]) within each group. In other words, I need to get the list

my_new_list= [('a', 4), ('x', 3), ('y', 3), ('z', 3), ('o', 2), ('p', 2)].

How can I write the sorted function with the proper lambda? I can't write just my_list.sort(key=lambda item: item[0]) because it will break the descending order of the tuples when they are sorted by their second elements.

What should my lambda look like?

alekscooper
  • 795
  • 1
  • 7
  • 19

2 Answers2

1
my_list = [('a', 4), ('z', 3), ('y', 3), ('x', 3), ('p', 2), ('o', 2)]

my_list = sorted(my_list, key=lambda k: (-k[1], k[0]))
print(my_list)

Prints:

[('a', 4), ('x', 3), ('y', 3), ('z', 3), ('o', 2), ('p', 2)]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

Your key should be:

key=lambda item: (item[0], -item[1])
Serial Lazer
  • 1,667
  • 1
  • 7
  • 15