最有效的方式移除非数字列表项
我想要“清理”一个列表,排除掉任何包含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']
因为我将要处理的列表比较大(大约5000个项目),而且每个字符串都比较长(15个字符)。
3 个回答
-1
如果你想在输出中同时保留整数和浮点数:
def is_float(string):
try:
float(string)
return True
except:
return False
example_list = ['text', 'another text', '1', '2.980', '3']
output = [a for a in example_list if is_float(a)]
print(output)
# Output is: ['1', '2.980', '3']
另外,你也可以使用 filter
,正如 eumiro 建议的:
output = list(filter(is_float, example_list))
print(output)
# Output is: ['1', '2.980', '3']
致谢:is_float()
这个函数来自于 Saullo G. P. Castro 的这个 回答。
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
18
字符串方法 isdigit
有什么问题吗?
>>> ls = ['1a', 'b3', '1']
>>> cleaned = [ x for x in ls if x.isdigit() ]
>>> cleaned
['1']
>>>