Python 删除非数字列表项的最有效方法
我希望通过排除任何包含0-9以外字符的项目来“清理”列表,并想知道是否有比例如Python 删除非数字列表项的最有效方法,python,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'] 因为我将在长字符串(15个字符)的大型ish列表(5k项)上操作。字符串方法isdigit有什么问题吗 >>&
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个字符)的大型ish列表(5k项)上操作。字符串方法
isdigit
有什么问题吗
>>> ls = ['1a', 'b3', '1']
>>> cleaned = [ x for x in ls if x.isdigit() ]
>>> cleaned
['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']
参考:+1,另一种可能是
cleaned=filter(str.isdigit,ls)
@eumiro,没错,但这两种方法都不太像Pythonic,而且只适用于精确的str
对象--@MattH的解决方案适用于str
,unicode
,以及任何其他具有isdigit()
方法(duck-typing)的对象。