Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max in a list with two conditions

Tags:

python

list

max

I have a list in Python in which each element is a tuple like this:

(attr1, attr2, attr3)

I want to find the tuple that has the largest attr2, but that have attr3 >= 100.

What is the pythonic approach to this?

like image 270
iomartin Avatar asked Sep 17 '12 12:09

iomartin


1 Answers

You have to both filter and use a key argument to max:

from operator import itemgetter

max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))

The filter can also be expressed as a generator expression:

max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))

Demo:

>>> yourlist = [(1, 2, 300), (2, 3, 400), (3, 6, 50)]
>>> max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))
(2, 3, 400)
>>> max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))
(2, 3, 400)

Note that because you filter, it's easy to end up with an empty list to pick the max from, so you may need to catch ValueErrors unless you need that exception to propagate up the call stack:

try:
    return max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))
except ValueError:
    # Return a default
    return (0, 0, 0)
like image 173
Martijn Pieters Avatar answered Sep 30 '22 02:09

Martijn Pieters