[英]Most efficient way to remove non-numeric list entries
我想通过排除任何包含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个)。
字符串方法isdigit
吗?
>>> ls = ['1a', 'b3', '1']
>>> cleaned = [ x for x in ls if x.isdigit() ]
>>> cleaned
['1']
>>>
您可以使用等数字函数。 它检查字符串是否仅包含数字字符。 此方法仅在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.