如何在元素总和最大的列表列表中找到列表?
问题描述:
我有一个列表列表:
x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]
我想获取其元素之和在列表中最大的列表.在这种情况下,[7,8,9]
.
I want to get the list whose sum of its elements is the greatest in the list. In this case [7,8,9]
.
我宁愿花哨的map
或lambda
或列表理解方法,而不是for/while/if
循环.
I'd rather have a fancy map
or lambda
or list comprehension method than a for/while/if
loop.
最好的问候
答
max
接受关键参数,通过它您可以告诉max如何计算可迭代项中每个项目的值. sum
在这里效果很好:
max
takes a key argument, with it you can tell max how to calculate the value for each item in an iterable. sum
will do nicely here:
max(x, key=sum)
演示:
>>> x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]
>>> max(x, key=sum)
[7, 8, 9]
如果您需要使用不同的方法来汇总项目,也可以指定自己的函数;这不仅限于python内置函数:
If you need to use a different method of summing your items, you can specify your own functions too; this is not limited to the python built-in functions:
>>> def mymaxfunction(item):
... return sum(map(int, item))
...
>>> max([['1', '2', '3'], ['7', '8', '9']], key=mymaxfunction)
['7', '8', '9']