使用列表理解。嵌套如果

Using list comprehension. with nested if

给定文件名列表,我们想将所有扩展名为 hpp 的文件重命名为扩展名为 h。为此,我们希望生成一个名为 newfilenames 的新列表,其中包含新文件名。使用列表理解#

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
newfilenames = [filename[:len(filename) - 3] + "h" for filename in filenames if filename.endswith("p")]
print(newfilenames)

输出来了["stdio.h", "sample.h", "math.h"] 应该是 ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

我觉得你需要

filenames = [i[:-3]+"h" if i.split(".")[-1]=="hpp" else i for i in filenames]

print(filenames)

您只需将 .hpp 替换为 .h

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
x=[x.replace(".hpp",".h") for x in filenames]
print (x)

输出:

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