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

列表推导式中用replace与if/else替换文件名后缀报错求助

问题:列表推导式替换文件名后缀出错

需求:用列表推导式将文件名中的.hpp后缀替换为.h,其余文件名保持不变。

尝试的代码:

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
new_filenames = [name.replace("hpp", "h") for name in filenames if name.endswith("hpp") else name for name in filenames]
print(new_filenames)

期望输出:

["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

去掉else后的实际输出:

["stdio.h", "sample.h", "math.h"]

报错信息:

RuntimeErrorElement(RuntimeError,Error on line 6:
new_filenames = [name.replace("hpp", "h") for name in filenames if name.endswith("hpp") else name for name in filenames]
^
SyntaxError: invalid syntax
)

错误原因及解决方法

你写的列表推导式语法结构错误,把三元表达式的位置搞反了。正确的带条件的列表推导式结构应该是:[表达式1 if 条件 else 表达式2 for 元素 in 序列],而非将else放在if过滤条件之后再重复遍历序列。

另外直接替换"hpp"会误改hpp.out这类文件名,建议精准匹配.hpp后缀。正确代码如下:

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
new_filenames = [name.replace(".hpp", ".h") if name.endswith(".hpp") else name for name in filenames]
print(new_filenames)

运行后就能得到预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:15:53