alex1997 alex1997 - 1 month ago 6
Python Question

Python, how to sort a list based on a sum

a = [('dog', 4, 5), ('cat', 1, 3), ('house', 6, 3), ('car', 1, 1), ('boyfriend', 2, 2), ('doll', 1, 1)


How can i sort this list in a descending order based on the sum between the two numbers and, if the sum is the same, how can i sort it based on the first element?

My list should be:

a = [('dog', 4, 5), ('house', 6, 3), ('boyfriend', 2, 2), ('cat', 1, 3), ('car', 1, 1), ('doll', 1, 1)

Answer

Use the custom key function returning a tuple where the first item is the sum and the second is the first item of each subelement:

In [2]: sorted(a, key=lambda item: (-(item[1] + item[2]), item[0]))
Out[2]: 
[('dog', 4, 5),
 ('house', 6, 3),
 ('boyfriend', 2, 2),
 ('cat', 1, 3),
 ('car', 1, 1),
 ('doll', 1, 1)]

Note that we are returning the negative sum to reverse-sort by the sum and keeping the requirement for the secondary key sort to be ascending.