python-3.x - 当尝试将任何元素附加和删除到列表时,它会跳过 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']
解决方案
我可以用:
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']
但是谁能帮我我错过了什么???
推荐阅读
- salesforce - 如何将重力表单的隐藏字段值发送到 Salesforce?
- html - Google Web App - 用于从 Google 电子表格中过滤数据的搜索框
- java - Java AppCDS 存档可以由不同的程序共享吗?
- regex - 如何拒绝名为“!”的文件 用 wget?
- redis - 带有 Redis 的 Apollo 服务器数据源
- mongodb - 数据未按要求更新到集合
- android - uiautomatorviewer.bat 显示自北极狐以来的错误
- javascript - 饼图没有弹出 HighCharts
- reactjs - Chart.js 圆环图渲染错误
- android - Android Studio 中意外删除的搁置更改