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?)
. (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:
newlist= [i for i in mylist if i.isdigit()]
but I ended up having 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?
I am using 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.
mylist[:]
changes the original list which may or may not be what you want, if you want to keep both just use newlist= ...
.
For Your example list this can apply, "without using too many if/else or try/except clauses"
>>>[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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.