从列表中删除NoneType元素的本机Python函数? [英] Native Python function to remove NoneType elements from list?

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

问题描述

我正在Python中使用Beautiful Soup从HTML文件中抓取一些数据.在某些情况下,Beautiful Soup会返回同时包含stringNoneType对象的列表.我想过滤掉所有NoneType对象.

I'm using Beautiful Soup in Python to scrape some data from HTML files. In some cases, Beautiful Soup returns lists that contain both string and NoneType objects. I'd like to filter out all the NoneType objects.

在Python中,包含NoneType对象的列表是不可迭代的,因此列表理解不是此选项.具体来说,如果我有一个包含NoneTypes的列表lis,并且尝试执行类似[x for x in lis (some condition/function)]的操作,Python会抛出错误TypeError: argument of type 'NoneType' is not iterable.

In Python, lists with containing NoneType objects are not iterable, so list comprehension isn't an option for this. Specifically, if I have a list lis containing NoneTypes, and I try to do something like [x for x in lis (some condition/function)], Python throws the error TypeError: argument of type 'NoneType' is not iterable.

正如我们在其他帖子中看到的那样,很容易在用户定义的功能.这是我的味道:

As we've seen in other posts, it's straightforward to implement this functionality in a user-defined function. Here's my flavor of it:

def filterNoneType(lis):
    lis2 = []
    for l in links: #filter out NoneType
        if type(l) == str:
            lis2.append(l)
    return lis2

但是,我想为此使用内置的Python函数.我总是喜欢在可能的情况下简化我的代码. Python是否具有可以从列表中删除NoneType对象的内置函数?

However, I'd love to use a built-in Python function for this if it exists. I always like to simplify my code when possible. Does Python have a built-in function that can remove NoneType objects from lists?

推荐答案

我认为最简单的方法是:

I think the cleanest way to do this would be:

#lis = some list with NoneType's
filter(None, lis)

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

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