1

这样做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'.

我错过了什么?

PS尝试except了没有参数,结果是一样的。

4

2 回答 2

2

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

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
于 2018-10-19T11:19:31.277 回答
1

当你修改一个你正在迭代的列表时,Python 不喜欢它,因为它不知道它要去哪里并且会感到困惑。

解决此问题的最简单但不是最有效的方法是遍历列表的副本:

dirlist = ['lines-data', 'abgafhb', 'tmp-data.tar', '100', '115.4', '125']
for x in dirlist[:]:  # Note the [:]
    try:
        float(x)
    except (ValueError, TypeError):
        dirlist.remove(x)
print dirlist
于 2018-10-19T11:20:33.277 回答