Dami Devil
Dami Devil

Reputation: 47

Get min value based on condition

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

Upvotes: 2

Views: 1397

Answers (3)

Ali_Sh
Ali_Sh

Reputation: 2816

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).

Upvotes: 1

SergFSM
SergFSM

Reputation: 1491

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

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

Upvotes: 0

Cardstdani
Cardstdani

Reputation: 5223

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

Upvotes: 5

Related Questions