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?
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 ValueError
s 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With