Get min value based on condition

Viewed 99

I have the following list

L= [383, 590, 912, 618, 203, 982, 364, 131, 343, 202]

If I use the function min(L) I get 131

Is it possible to know the min value in the list of numbers that exceed 200? I guess something like min(L, Key>200)

The desired result would be 202

3 Answers

You can use the min() function in combination with a list traversal using a for loop as follows to introduce conditions when finding minimums:

L= [383, 590, 912, 618, 203, 982, 364, 131, 343, 202]
m = min(i for i in L if i > 200)
print(m)

Output:

202

If there is no limitation on using any other libraries, it can be easily achieved by indexing in NumPy:

import numpy as np

s = np.array(L)
s[s > 200].min()
# 202

Using NumPy on large arrays are much recommended, which can easily handle such problems in more efficient way in terms of performance and memory usage (on large arrays).

this solution isn't as fast as this one, just an alternative:

min(L, key=lambda x: x>200 and x or float('inf'))
Related