假设我有一个数组
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]。
2条答案
按热度按时间cwxwcias1#
您可以在列表解析中添加筛选条件:
ioekq8ef2#
另一种可能的解决方案:
输出: