Python:从列表中删除不可转换为int的项目的干净而有效的方法

Chr*_*ung 1 python integer list python-2.7

我有一个这样的列表:

mylist = [1.0,2.0,3.0,4.0,...,u'*52', u'14*', u'16*',"", "" ,"",...]
Run Code Online (Sandbox Code Playgroud)

它基本上包含float,, unicodesblank(string?).(它也可能有其他数据类型)

我的目标是从列表中删除任何不可转换为整数的项目.

我试过这样使用.isdigit():

newlist= [i for i in mylist if i.isdigit()]
Run Code Online (Sandbox Code Playgroud)

但我最终得到了AttributeError:

AttributeError: 'float' object has no attribute 'isdigit'
Run Code Online (Sandbox Code Playgroud)

什么是干净利落的方式(不使用太多if/else或try/except子句)来实现这一目标?

我正在使用python 2.7

Mar*_*ers 7

你可以使用辅助函数:

def convertible(v):
    try:
        int(v)
        return True
    except (TypeError, ValueError):
        return False

newlist = [i for i in mylist if convertible(i)]
Run Code Online (Sandbox Code Playgroud)