给定一个文件名列表,我们希望将所有扩展名为 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 扩展到 index[1] 处的 final_file?
有没有更简单的解决方案?