Reputation: 1599
In a list of python tuple, I need to find the tuple with min sum.
for example,
a = [ (2, 6) , (1,3) , (0,2) ]
(0, 2)
should be returned because its sum is minimal.
I know how to do it by list comprehension and then find the smallest tuple sum.
minTuple = min([((x[0] + x[1]), (x[0], x[1])) for x in a ], key = lambda x : x[0] )
I would like to do it by map/lambda and list comprehension.
How to implement it efficiently?
Upvotes: 1
Views: 624
Reputation: 1594
The simplest answer to your question is just to use the min()
function, provided with a key to the array. The key
parameter specifies a set of rules for comparison that min()
uses to evaluate the tuples.
See answer here.
min(a, key=sum)
Upvotes: 3
Reputation: 1087
Try this!
>>> a = [ (2, 6) , (1,3) , (0,2) ]
>>> min(a, key=sum)
(0, 2)
>>> a = [ (2, 6) , (1,3) , (0,7) ]
>>> min(a, key=sum)
(1, 3)
Upvotes: 2