在特定索引中扩展列表

Extend list in a specific index

给定一个文件名列表,我们想将所有扩展名为 hpp 的文件重命名为扩展名为 h。为此,我们希望生成一个名为 newfilenames 的新列表,其中包含新文件名。使用您目前学到的任何方法(例如 for 循环或列表推导)填写代码中的空白。

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
new_filename=[]
new_list=[]
final_file=[]
for element in filenames:
    if element.endswith("p"):
        new_filename.append(element)
for element1 in new_filename:
    new_list.append(element1.split("pp")[0])
for element3 in filenames:
    if not element3.endswith("p"):
        final_file.append(element3)
final_file.extend(new_list)
print(final_file)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

有什么方法可以将 new_list 扩展到索引 [1] 处的 final_file 吗?

有没有更简单的解决方案?

更简单的方法:

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
final_file=[]
for file in filenames:
    if file.endswith(".hpp"):
        final_file.append(file.replace('.hpp','.h'))
    else:
        final_file.append(file)

replace() 只会将 sub-string 替换为另一个