在特定索引中扩展列表

问题描述

给出一个文件名列表,我们想将所有扩展名为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()只会用另一个子字符串替换

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...