Python从列表中删除所有数字 [英] Python remove all numbers from a list

查看:2058
本文介绍了Python从列表中删除所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个unicode元素列表,我正在尝试从中删除所有整数. 我的代码是:

I have a list of unicode elements and I'm trying to remove all integer numbers from It. My code is:

List = [u'123', u'hello', u'zara', u'45.3', u'pluto']

for el in List:
   if isinistance(el, int):
      List.remove(el)

该代码不起作用,它给了我与u'123'include相同的列表. 我需要的是这样:

The code doesn't work, It give me the same list with u'123' include. What i need is this:

List = [ u'hello', u'zara', u'45.3', u'pluto']

有人可以帮我吗?

推荐答案

您列出的列表由unicode字符串组成,这些字符串显然不是int的实例.您可以尝试在辅助函数中将它们转换为int,并以此为条件删除它们/以构造新列表.

You list consists of unicode strings which are no instances of int obviously. You can try converting them to int in a helper function and use this as a condition to remove them/ to construct a new list.

def repr_int(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

original_list = [u'123', u'hello', u'zara', u'45.3', u'pluto']

list_with_removed_ints = [elem for elem in original_list if not repr_int(elem)]

这篇关于Python从列表中删除所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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