Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除非数字列表项的最有效方法_Python - Fatal编程技术网

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

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有什么问题吗 >>&

我希望通过排除任何包含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
有什么问题吗

>>> 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)的对象。