简体   繁体   English

通过Python中的元素总和查找列表列表的最大值

[英]Finding maximum of a list of lists by sum of elements in Python

What's the idiomatic way to do maximumBy (higher order function taking a comparison function for the test), on a list of lists, where the comparison we want to make is the sum of the list, in Python? 在列表列表中,执行maximumBy (更高阶函数采用测试的比较函数)的惯用方法是什么,我们想要进行的比较是Python中列表的总和?

Here's a Haskell implementation and example output: 这是一个Haskell实现和示例输出:

> maximumBy (compare `on` sum) [[1,2,3],[4,5,6],[1,3,5]]
> [4,5,6]

And implementations of those base library functions, just for completeness (in case you want to use reduce or something :) 这些基础库函数的实现,只是为了完整性(如果你想使用reduce或者东西:)

maximumBy cmp xs =  foldl1 maxBy xs
    where
       maxBy x y = case cmp x y of GT -> x; _ -> y

k `on` f = \x y -> f x `k` f y

sum      =  foldl' (+) 0

Since Python 2.5 you can use max with a key parameter: 从Python 2.5开始,您可以使用max和一个关键参数:

>>> max(a, key=sum)
[4, 5, 6]

它不是非常有效,但是:

reduce(lambda x,y: x if sum(x)>sum(y) else y, [[1,2,3],[4,5,6],[1,3,5]])

If max didn't have the key parameter you could code the DSU pattern explicitly: 如果max没有key参数,则可以显式编写DSU模式:

max(izip(imap(sum,a),a))[1]

izip and imap are from the itertools module in python 2 and do what zip and map do, but lazily using Python generators, to avoid consing an intermediate list. izipimap来自python 2中的itertools模块并执行zip和map的操作,但懒得使用Python生成器,以避免中间列表。 In Python 3, the map and zip builtins are lazy. 在Python 3中,map和zip builtins是懒惰的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM