Don Stewart
Don Stewart

Reputation: 137987

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

Upvotes: 15

Views: 3428

Answers (3)

solrize
solrize

Reputation: 11

If max didn't have the key parameter you could code the DSU pattern explicitly:

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. In Python 3, the map and zip builtins are lazy.

Upvotes: 1

outis
outis

Reputation: 77420

It isn't terribly efficient, but:

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

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838726

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

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

Upvotes: 41

Related Questions