简体   繁体   中英

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

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

>>> 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(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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