Output 1 if greater than certain threshold and 0 less than another threshold and ignore if in between these threshold

huangapple go评论69阅读模式
英文:

Output 1 if greater than certain threshold and 0 less than another threshold and ignore if in between these threshold

问题

output = [0 if x < threshold1 else 1 if x > threshold2 else 0 for x in arr]
英文:

Assume I have an array

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

I have two thresholds threshold1=0.25 and threshold2=0.35

I need to output an array which generates [0, 0, 1, 1]. If value in array arr is less than threshold1, then output array element should be 0 and if greater than threshold2, it should output 1.

I know a one liner code like output= [0 if x &lt; threshold else 1 for x in arr] but this generates 5 element output and is not correct. What is the correct way of doing this in one line?

I am expecting output [0, 0, 1, 1].

答案1

得分: 2

你可以在列表理解中添加筛选条件:

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]
英文:

You can add filter condition in a list comprehension:

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

threshold1=0.25
threshold2=0.35

output= [0 if x &lt; threshold1 else 1 for x in arr if x &lt; threshold1 or x &gt; threshold2]

print(output) # [0, 0, 1, 1]

答案2

得分: 0

另一种可能的解决方案:

[x for x in [0 if y &lt; threshold1 else 
             1 if y &gt; threshold2 else None for y in arr] if x is not None]

输出:

[0, 0, 1, 1]
英文:

Another possible solution:

[x for x in [0 if y &lt; threshold1 else 
             1 if y &gt; threshold2 else None for y in arr] if x is not None]

Output:

[0, 0, 1, 1]

huangapple
  • 本文由 发表于 2023年4月4日 18:16:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75928171.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定