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

Python按多条件从列表提取字符串及列表推导式语法错误解决

错误原因

  • Python中逻辑与、逻辑非运算符不是&&/!,对应要替换为and/not
  • 字符串方法startswith是函数调用,必须带括号,你写的mag.startswith"e_"属于语法错误,需要补全为mag.startswith("e_")

最简实现

直接用单个列表推导式就能完成筛选,不需要拆分两个列表再合并:

magnames = [s for s in fields if s.startswith('Fp') or (s.endswith('mag') and not s.startswith('e_'))]

如果你要保留原来的拆分写法,把magnames2的语法修正即可:

magnames2 = [mag for mag in fields if mag.endswith('mag') and not mag.startswith("e_")]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:36:05