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

如何在AppleScript中检测并过滤Python脚本返回的NaN值

解决方法

方案1:调用阶段直接过滤(最简便)

直接在shell调用环节过滤掉nan行,不需要修改现有AppleScript处理逻辑,性能最高。

-- 用grep直接过滤掉所有内容为nan的行,返回结果中已无nan项
set theParagraphs to paragraphs of (do shell script "/usr/local/bin/python3.9 /path/to/my/file.py | grep -v '^nan$'")

方案2:AppleScript内检测nan

你之前的判断失效是因为先将内容转为了数字类型,再和字符串"nan"比对必然返回false,只需要调整判断顺序,强制转字符串比对即可:

set theParagraphs to paragraphs of (do shell script "/usr/local/bin/python3.9 /path/to/my/file.py")
set filteredList to {}
repeat with currentItem in theParagraphs
    -- 先判断原始字符串是否为nan,跳过对应项
    if currentItem as string is not equal to "nan" then
        -- 后续你的数值处理逻辑
        set end of filteredList to currentItem as number
    end if
end repeat
-- filteredList就是已经过滤掉nan的数值列表

之前判断失效的原因说明:

  • 你尝试的currentItem is equal to "nan"返回false,是因为你已经先把currentItem转成了数字类型,数字和字符串比对永远不相等
  • AppleScript对NaN的数值比较做了特殊处理,所以nan = nan或者nan ≠ nan的判断都不会返回预期结果,不要用数值比较的方式判断NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:15:02