大于某个阈值输出1,小于另一个阈值输出0,在两个阈值之间输出忽略



假设我有一个数组

arr = [0.1, 0.2, 0.3, 0.4, 0.5]

我有两个阈值threshold1=0.25和threshold2=0.35

我需要输出一个数组,生成[0,0,1,1]。如果数组arr中的value小于threshold1,则输出数组元素应为0,如果大于threshold2,则输出1。

我知道像output= [0 if x < threshold else 1 for x in arr]这样的一行代码,但这产生5个元素的输出,是不正确的。在一行中正确的方法是什么?

我想要输出[0,0,1,1].

可以在列表推导式中添加过滤条件:

arr = [0.1, 0.2, 0.3, 0.4, 0.5]
threshold1=0.25
threshold2=0.35
output= [0 if x < threshold1 else 1 for x in arr if x < threshold1 or x > threshold2]
print(output) # [0, 0, 1, 1]

另一个可能的解决方案:

[x for x in [0 if y < threshold1 else 
1 if y > threshold2 else None for y in arr] if x is not None]

输出:

[0, 0, 1, 1]

最新更新