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
相关产品推荐
相关产品推荐

