Python, how to sort a list based on a sum

后端 未结 1 1710
梦如初夏
梦如初夏 2021-01-19 15:31
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 de

相关标签:
1条回答
  • 2021-01-19 15:45

    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.

    0 讨论(0)
提交回复
热议问题