[英]Python : Clean and efficient way to remove items that are not convertable to int from list
I have a list like this: 我有一个这样的清单:
mylist = [1.0,2.0,3.0,4.0,...,u'*52', u'14*', u'16*',"", "" ,"",...]
It basically contains, float
, unicodes
and blank(string?)
. 它基本上包含
float
, unicodes
和blank(string?)
。 (It could have other data types as well) (它也可以具有其他数据类型)
My objective is to remove any item which are not convertible to integer from the list. 我的目标是从列表中删除所有不能转换为整数的项目。
I have tried using .isdigit()
like this: 我试过像这样使用
.isdigit()
:
newlist= [i for i in mylist if i.isdigit()]
but I ended up having AttributeError
: 但是我最终遇到了
AttributeError
:
AttributeError: 'float' object has no attribute 'isdigit'
What would be a clean and neat way (without using too many if/else or try/except clauses) to achieve this? 什么是一种干净整洁的方式(不使用太多的if / else或try / except子句)来实现这一目标?
I am using python 2.7 我正在使用python 2.7
You could use a helper function: 您可以使用一个辅助函数:
def convertible(v):
try:
int(v)
return True
except (TypeError, ValueError):
return False
newlist = [i for i in mylist if convertible(i)]
from numbers import Number
mylist = [1.0,2.0,3.0,4.0,u'*52', u'14*', u'16*',"", "" ,""]
mylist[:] = [ele for ele in mylist if isinstance(ele,Number)]
print(mylist)
Why you get the AttributeError: 'float' object has no attribute 'isdigit'
is because isdigit
is a str method, you are trying to call it on an actual float. 为什么会出现
AttributeError: 'float' object has no attribute 'isdigit'
的原因是因为isdigit
是str方法,因此您试图在实际的float上调用它。
mylist[:]
changes the original list which may or may not be what you want, if you want to keep both just use newlist= ...
. mylist[:]
更改原始列表(可能想要也可能不是您想要的),如果要同时保留两者,请使用newlist= ...
For Your example list this can apply, "without using too many if/else or try/except clauses" 对于您的示例列表,这可以适用,“无需使用过多的if / else或try / except子句”
>>>[i for i in mylist if isinstance(i, (int, float))]
[1.0, 2.0, 3.0, 4.0]
Try the following code: 尝试以下代码:
mylist = [1.0,2.0,3.0,4.0,u'*52', u'14*', u'16*']
newlst=[]
for i in mylist:
try:
newlst.append(int(i))
except ValueError:
pass
print newlst
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.