问题描述
给出一个文件名列表,我们想将所有扩展名为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","math.h","hpp.out"]
有什么方法可以将new_list扩展到index [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()只会用另一个子字符串替换