2011-05-17 71 views
5

我期待通過排除任何包含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項目)上操作。

回答

11

字符串方法isdigit有什麼問題嗎?

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

是的,這會做得很好。 – urschrei 2011-05-17 12:05:36

+1

+1,另一種可能性是'清理=過濾器(str.isdigit,ls)' – eumiro 2011-05-17 12:07:08

+1

@eumiro,true,但這不但Pythonic並且只適用於確切的'str'對象 - @MartH的解決方案適用於'str ','unicode'和其他有'isdigit()'方法的對象(鴨子打字)。 – 2011-05-17 14:51:07

0

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

相關問題