Reputation: 574
This may be a simple question but, let us say that we have an array :
a = [0,10,20]
What is the simplest way to retrieve the least value which is greater than 0?. In this case, it would be 10.
Upvotes: 1
Views: 787
Reputation: 126
Not pretty
a = [0, 10, 20]
def find_lowest_num(a):
lowest_num = None
for element in a:
if lowest_num is None and element > 0:
lowest_num = element
elif lowest_num is None and element == 0:
pass
else:
if element < lowest_num and element > 0:
lowest_num = element
return lowest_num
print(find_lowest_num(a))
Upvotes: 2
Reputation: 1466
I can try like this without using numpy.
def findValue():
a = [0,10,5,20]
a.sort()
noToCheck = 0
for i in a:
if i > noToCheck :
print("Found value: ", i)
break
findValue()
Upvotes: 3
Reputation: 26047
Or a min
on generator:
min(x for x in a if x > 0)
Example:
a = [0,10,20]
print(min(x for x in a if x > 0))
# 10
Upvotes: 3
Reputation: 17911
You can use the min()
function with a key:
min(a, key=lambda x: float("inf") if x<=0 else x)
Upvotes: 1
Reputation: 36704
Since you included Numpy in your tags, I'm assuming you're OK with a solution with Numpy?
import numpy as np
a = np.array([0,10,20])
np.min(a[a > 0])
Out[1]: 10
Upvotes: 2