列表推导式中用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
相关产品推荐
相关产品推荐

