[英]How to find the list in a list of lists whose sum of elements is the greatest?
我有一份清單清單:
x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]
我想得到列表中其元素總和最大的列表。 在這種情況下[7,8,9]
。
我寧願有一個花哨的map
或lambda
或列表理解方法而不是for/while/if
循環。
最好的祝福
max
接受一個關鍵參數 ,用它可以告訴max如何計算iterable中每個項的值。 sum
將在這里做得很好:
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內置函數:
>>> def mymaxfunction(item):
... return sum(map(int, item))
...
>>> max([['1', '2', '3'], ['7', '8', '9']], key=mymaxfunction)
['7', '8', '9']
為了完整性,並且@Martijn打敗了我最優雅的答案 - 我只是在key=
參數在Python中可用之前拋出選項(但如果你使用<2.5 - 你應該真的升級)以及它有多難看用來:
x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]
with_idx = ( (sum(v), i) for i,v in enumerate(x))
print x[max(with_idx)[1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.