python: 数组指定范围内的最小值

python: minimum value within specified bounds for an array

假设我有一个数组 a = [-1.2, 1, 0.5, 4, 5, 3]

有没有办法找到 a=0.2 到 b=2 之间的最小元素

在此特定示例中,答案将为 0.5。

我想在 python 中执行此计算。 .

a = [-1.2, 1, 0.5, 4, 5, 3]
r1=0.2 
r2=2
l=[]
for i in a:
    if i>r1 and i<r2:
        l.append(i)
print(min(l))

我已经严格考虑了两个给定值,如果要包含两者,请使用 >=<=。希望这有帮助

如果你用你的边界扩展列表(Min=0.2Max=2),你可以在对扩展列表进行排序后通过索引获取它们之间的元素:

a =  [-1.2, 1, 0.5, 4, 5, 3]
# define bounds
Min = 0.2
Max = 2
# extend list with bounds
a.extend([Min, Max])
# sort list (default: ascending)
a = sorted(a)
# slicing
print(min(a[a.index(Min)+1:a.index(Max)]))
# 0.5

您可以对其余元素使用 filter(predicate, list) or a generator expression to eliminate the out-of-bounds values, then use min(iterable)

a = [-1.2, 1, 0.5, 4, 5, 3]
assert 0.5 == min(filter(lambda x: 0.2 <= x <= 2, a))
# or
assert 0.5 == min(x for x in a if 0.2 <= x <= 2)

如果你会用numpy:

a = np.array([-1.2, 1, 0.5, 4, 5, 3])
min(a[(a<2) & (a > 0.2)])