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

Python:从列表中删除不可转换为int的项目的干净而有效的方法 (Python : Clean and efficient way to remove items that are not convertable to int from list)

问题

我有一个这样的列表:

mylist = [1.0,2.0,3.0,4.0,...,u'*52', u'14*', u'16*',"", "" ,"",...]

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

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

我试过这样使用.isdigit()

newlist= [i for i in mylist if i.isdigit()]

但我最终得到了AttributeError

AttributeError: 'float' object has no attribute 'isdigit'

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

我正在使用python 2.7

解决方法

你可以使用辅助函数:

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

newlist = [i for i in mylist if convertible(i)]

问题

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)]
相似信息