user2290820
user2290820

Reputation: 2759

Python: Maximum of lists of 2 or more elements in a tuple using key

Lets say i have a tuple of list like:

g = (['20', '10'], ['10', '74'])

I want the max of two based on the first value in each list like

max(g, key = ???the g[0] of each list.something that im clueless what to provide)

And answer is ['20', '10'] Is that possible? what should be the key here? According to above answer.

Another eg:

g = (['42', '50'], ['30', '4'])
ans: max(g, key=??) = ['42', '50']

PS: By max I mean numerical maximum.

Upvotes: 2

Views: 1651

Answers (4)

dawg
dawg

Reputation: 104092

If by 'max' you mean lexicographic max:

>>> max(['0','5','10','100'])
'5'
>>> min(['0','5','10','100'])
'0'

Then you can just use max with no key function at all:

>>> max((['20', '10'], ['10', '74']))
['20', '10']
>>> max((['42', '50'], ['30', '4']))
['42', '50']

If you mean numerical max, use a lambda:

>>> max((['0','10'],['5','100'],['100','1000']))
['5', '100']
>>> max((['0','10'],['5','100'],['100','1000']),key=lambda l:int(l[0]))
['100', '1000']    

Upvotes: 1

Eric
Eric

Reputation: 97661

If you store numbers as numbers:

g = ([20, 10], [10, 74])
max(g)

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

You can use lambda to specify which item should be used for comparison:

>>> g = (['20', '10'], ['10', '74'])
>>> max(g, key = lambda x:int(x[0]))  #use int() for conversion
['20', '10']

>>> g = (['42', '50'], ['30', '4'])
>>> max(g, key = lambda x:int(x[0]))
['42', '50']

You can also use operator.itemegtter, but in this case it'll not work as the items are in string form.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124548

Just pass in a callable that gets the first element of each item. Using operator.itemgetter() is easiest:

from operator import itemgetter

max(g, key=itemgetter(0))

but if you have to test against integer values instead of lexographically sorted items, a lambda might be better:

max(g, key=lambda k: int(k[0]))

Which one you need depends on what you expect the maximum to be for strings containing digits of differing length. Is '4' smaller or larger than '30'?

Demo:

>>> g = (['42', '50'], ['30', '4'])
>>> from operator import itemgetter
>>> max(g, key=itemgetter(0))
['42', '50']
>>> g = (['20', '10'], ['10', '74'])
>>> max(g, key=itemgetter(0))
['20', '10']

or showing the difference between itemgetter() and a lambda with int():

>>> max((['30', '10'], ['4', '10']), key=lambda k: int(k[0]))
['30', '10']
>>> max((['30', '10'], ['4', '10']), key=itemgetter(0))
['4', '10']

Upvotes: 6

Related Questions