Max listed with two conditions

I have a list in Python in which each element is a tuple as follows:

(attr1, attr2, attr3) 

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

What is the pythonic approach to this?

+6
source share
1 answer

You need to both filter and use the key argument for max:

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

A 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 since you are filtering, it is easy to get an empty list to select max from, so you might need to catch a ValueError if you don't need this exception to propagate 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) 
+13
source

Source: https://habr.com/ru/post/925573/


All Articles