首页 > 解决方案 > 当尝试将任何元素附加和删除到列表时,它会跳过 Python 中的一个特定值

问题描述

我正在尝试用“.h”扩展名替换“.hpp”扩展名。但是,一旦我尝试添加“filenames.remove(i_new)”行,它就会跳过一个特定的值“sample.hpp”。这是我的代码:

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.
for i in filenames:
    if i[-3:] == "hpp":
        print(i)
        i_new = i[:-3]+"h"
        print(i_new)
        filenames.append(i_new)
        print(filenames)
for i in filenames:
    if i[-3:] == "hpp":
        print(i)
        filenames.remove(i)
        print(filenames)

print('new_filenames', filenames)

这是输出:

stdio.hpp
stdio.h
['program.c', 'stdio.hpp', 'sample.hpp', 'a.out', 'math.hpp', 'hpp.out', 'stdio.h']
sample.hpp
sample.h
['program.c', 'stdio.hpp', 'sample.hpp', 'a.out', 'math.hpp', 'hpp.out', 'stdio.h', 'sample.h']
math.hpp
math.h
['program.c', 'stdio.hpp', 'sample.hpp', 'a.out', 'math.hpp', 'hpp.out', 'stdio.h', 'sample.h', 'math.h']
stdio.hpp
['program.c', 'sample.hpp', 'a.out', 'math.hpp', 'hpp.out', 'stdio.h', 'sample.h', 'math.h']
math.hpp
['program.c', 'sample.hpp', 'a.out', 'hpp.out', 'stdio.h', 'sample.h', 'math.h']
new_filenames ['program.c', 'sample.hpp', 'a.out', 'hpp.out', 'stdio.h', 'sample.h', 'math.h']

标签: python-3.xlist

解决方案


我可以用:

new_filenames = [i.replace('.hpp','.h') for i in filenames]
print('new_filenames', newfilenames)

输出是:

['program.c', 'stdio.h', 'sample.h', 'a.out', 'math.h', 'hpp.out']

这是另一种方式,使用“hpp.hpp”:

filenames = ["program.c", "stdio.hpp","hpp.hpp" ,"sample.hpp", "a.out", "math.hpp", "hpp.out"]
newfilenames = []
#  newfilenames as a list containing the new filenames

for i in filenames:
    if i[-4:] == ".hpp":
        i = i[:-2]
        newfilenames.append(i)
    else:  newfilenames.append(i) 

print(newfilenames) 

输出是:

['program.c', 'stdio.h', 'hpp.h', 'sample.h', 'a.out', 'math.h', 'hpp.out']

但是谁能帮我我错过了什么???


推荐阅读