2011-05-17 57 views
5

我期待通过排除任何包含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'] 

因为我将在长字符串(15个字符)的大列表(5k项目)上操作。

回答

11

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

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

是的,这会做得很好。 – urschrei 2011-05-17 12:05:36

+1

+1,另一种可能性是'清理=过滤器(str.isdigit,ls)' – eumiro 2011-05-17 12:07:08

+1

@eumiro,true,但这不但Pythonic并且只适用于确切的'str'对象 - @MartH的解决方案适用于'str ','unicode'和其他有'isdigit()'方法的对象(鸭子打字)。 – 2011-05-17 14:51:07

0

您可以使用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

相关问题