Python,如何基于总和对列表进行排序 [英] Python, how to sort a list based on a sum
本文介绍了Python,如何基于总和对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
我的清单应该是:
a = [('dog', 4, 5), ('house', 6, 3), ('boyfriend', 2, 2), ('cat', 1, 3), ('car', 1, 1), ('doll', 1, 1)
推荐答案
使用自定义key
函数返回 tuple ,其中第一项是总和,第二个是每个子元素的第一项:
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.
这篇关于Python,如何基于总和对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文