首页 > 解决方案 > 使用 isdigit() 字符串方法时出现错误

问题描述

不是超级有经验,但我在使用 isdigit() 方法时遇到了一个错误。

我正在尝试浏览一个列表并删除所有非数字,但是我的最终列表不断给我一些字母。不确定这是一个错误还是我做错了什么。

这是我当前的python:

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

我的代码:

>>> test
['b', 'd', 'f', 'h', 'j', 'l', 'x', '2']
>>> for i in test:
if not i.isdigit():
    print(i, "should not be a digit")
    test.remove(i)


b should not be a digit
f should not be a digit
j should not be a digit
x should not be a digit
>>> test
['d', 'h', 'l', '2']

在这里,我希望我的最终列表中只有 2 个。我做错了吗?

标签: pythonarraysstring

解决方案


如果你想过滤掉一个isdigit测试:

test = list(filter( lambda x : x.isdigit(), test))

正如评论中所说,在迭代时删除元素是不好的做法。


推荐阅读