Python 3.x 在特定索引中扩展列表

Python 3.x 在特定索引中扩展列表,python-3.x,file,indexing,extend,coursera-api,Python 3.x,File,Indexing,Extend,Coursera Api,给定一个文件名列表,我们希望将扩展名为hpp的所有文件重命名为扩展名为h。为此,我们希望生成一个名为newfilename的新列表,该列表由新文件名组成。使用迄今为止所学的任何方法(如for循环或列表理解)填充代码中的空格 filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out&

给定一个文件名列表,我们希望将扩展名为hpp的所有文件重命名为扩展名为h。为此,我们希望生成一个名为newfilename的新列表,该列表由新文件名组成。使用迄今为止所学的任何方法(如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"]
有没有办法将新的_列表扩展到索引[1]处的最终_文件


有更简单的解决方案吗?

一种更简单的方法:

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()将用另一个子字符串替换一个子字符串

对此可能有一行解决方案,但我不建议使用它,因为这似乎是为循环和其他python内容的增量学习而做的赋值。您可以使用if-else语句在一个for循环中轻松解决此问题。在第一个循环中,您已经朝着正确的方向开始了。只需将第一条if语句扩展到:
if元素.endswith(“.hpp”):
,那么您将匹配所有要匹配的文件,并且可以将该字符串的切片版本附加到新列表中。然后你可以在else-statement中将所有其他文件添加到同一列表中。谢谢你的建议,我希望找到一种更简单的方法。你是对的,我错过了该文件的名称可以包含hpp,我刚刚编辑了答案,谢谢!!如果在文件名中的任何位置找到更新的代码,则更新的代码仍将替换
hpp
。现在唯一的区别是它还必须以
hpp
结束。OP问题的主要目的是只更改扩展名为
hpp
的文件。如果列表中有以下任何文件,则不应更改它们:
[“file.hhpp”,“ffshhp”]
,而以下文件只应更改扩展名:
[“.hhp.hhp”,“fishhp.hhp”]
我以前添加了点,现在应该可以了,除非名称包含.hpp,我认为它不太可能是anks,这对我是一个很大的帮助,我是一个初学者谢谢你的建议