删除非数字列表条目的最有效方法

时间:2011-05-17 11:26:37

标签: python

我希望通过排除任何包含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 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:1)

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

相关问题