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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You have to both filter and use a
keyargument to max:The filter can also be expressed as a generator expression:
Demo:
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: