pythonlisthigher-order-functions

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?

Here's a Haskell implementation and example output:

> 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 :)

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

Solution

  • Since Python 2.5 you can use max with a key parameter:

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