英文:
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 < 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 < threshold1 else 1 for x in arr if x < threshold1 or x > threshold2]
print(output) # [0, 0, 1, 1]
答案2
得分: 0
另一种可能的解决方案:
[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]
英文:
Another possible solution:
[x for x in [0 if y < threshold1 else
1 if y > threshold2 else None for y in arr] if x is not None]
Output:
[0, 0, 1, 1]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论