gpt4 book ai didi

python - 为什么这个浮点转换异常没有被很好地捕获?

转载 作者:行者123 更新时间:2023-11-30 22:05:48 25 4
gpt4 key购买 nike

Python 2.7.15中执行此操作:

dirlist = ['lines-data', 'abgafhb', 'tmp-data.tar', '100', '115.4', '125']
for x in dirlist:
try:
float(x)
except (ValueError, TypeError):
dirlist.remove(x)
print dirlist

结果:

['abgafhb', '100', '115.4', '125']

再次运行for循环会清除'abgafhb'

我错过了什么?

附注尝试不带任何参数的 except ,结果是相同的。

最佳答案

您不应修改正在迭代的列表。也许将成功的值存储在新列表中。

dir_list = ['lines-data', 'abgafhb', 'tmp-data.tar', '100', '115.4', '125']
new_list = []

for x in dir_list:
try:
float(x)
new_list.append(x)
except (ValueError, TypeError):
pass

print dir_list # will not have changed
print new_list # will contain only strings that can be converted to float

关于python - 为什么这个浮点转换异常没有被很好地捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52891252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com