去除非数字列表项的最有效方法

13

我想要通过排除任何包含0-9数字以外字符的项来“清理”一个列表,并且想知道是否有比例如下更有效的方式:

import re
invalid = re.compile('[^0-9]')    
ls = ['1a', 'b3', '1']
cleaned = [i for i in ls if not invalid.search(i)]
print cleaned
>> ['1']

因为我将要处理一些较大的列表(5k个元素),这些元素都是长字符串(15个字符)。

2个回答

19

isdigit字符串方法有什么问题吗?

>>> ls = ['1a', 'b3', '1']
>>> cleaned = [ x for x in ls if x.isdigit() ]
>>> cleaned
['1']
>>>

2
+1,另一种可能是cleaned = filter(str.isdigit, ls) - eumiro
1
@eumiro,没错,但这既不太符合Python的风格,也仅适用于确切的“str”对象 - @MattH的解决方案适用于“str”,“unicode”和任何具有“isdigit()”方法(鸭子类型)的其他对象。 - Ben Hoyt

2

您可以使用isnumeric函数。它会检查字符串是否只包含数字字符。该方法仅适用于Unicode对象,不能用于整数或浮点数值。

myList = ['text', 'another text', '1', '2.980', '3']
output = [ a for a in myList if a.isnumeric() ]
print( output )      
# Output is : ['1', '3']

参考:https://www.tutorialspoint.com/python/string_isnumeric.htm

string.isnumeric()方法用于检查字符串是否只包含数字字符。这个方法只能判断Unicode数字,也就是说除了0到9这几个数字之外的其他数字,比如罗马数字IV、中文数字四,它都无法识别。如果字符串不包含数字字符,则该方法返回False。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接