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

查看:222
本文介绍了Python:从列表中删除不可转换为int的项目的干净而有效的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

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

它基本上包含, float unicodes 空白(字符串?)。 (它可能还有其他数据类型)

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.

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

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

但是我最终得到 AttributeError

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

什么是干净利落的方式(不使用太多if / else或尝试/除了条款)来实现这个目标?

What would be a clean and neat way (without using too many if/else or try/except clauses) to achieve this?

我使用的是python 2.7

I am using 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)]

这篇关于Python:从列表中删除不可转换为int的项目的干净而有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆