You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用Python单行代码实现双阈值数组过滤转换

解决方法

直接在列表推导式中加入过滤逻辑,先剔除介于两个阈值之间的元素,再对符合条件的元素赋值:

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]

代码说明

  • 末尾的if x < threshold1 or x > threshold2是过滤条件,直接排除掉threshold1 ≤ x ≤ threshold2的元素(即示例中的0.3)
  • 前面的0 if x < threshold1 else 1负责给保留的元素分配对应值:小于threshold1的输出0,大于threshold2的输出1

运行后output的结果即为[0, 0, 1, 1],完全符合需求。

内容的提问来源于stack exchange,提问作者usrp_hacker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:12:01