从列表中删除 NoneType 元素的本机 Python 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14229433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:49:51  来源:igfitidea点击:

Native Python function to remove NoneType elements from list?

pythonlistnonetype

提问by solvingPuzzles

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

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

In Python, lists with containing NoneTypeobjects are not iterable, so list comprehension isn't an option for this. Specifically, if I have a list liscontaining 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.

在 Python 中,包含NoneType对象的列表是不可迭代的,因此列表理解不是一个选项。具体来说,如果我有一个lis包含的列表NoneTypes,并且我尝试执行类似的操作[x for x in lis (some condition/function)],Python 会抛出错误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

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 NoneTypeobjects from lists?

但是,如果存在,我很乐意为此使用内置的 Python 函数。我总是喜欢尽可能简化我的代码。Python 是否具有可以NoneType从列表中删除对象的内置函数?

采纳答案by Abs

I think the cleanest way to do this would be:

我认为最干净的方法是:

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

回答by Charles Menguy

You can do this using list comprehension:

您可以使用列表理解来做到这一点:

clean = [x for x in lis if x != None]

As pointed in the comments you could also use is not, even if it essentially compiles to the same bytecode:

正如评论中指出的,您也可以使用is not,即使它基本上编译为相同的字节码:

clean = [x for x in lis if x is not None]

You could also used filter(note: this will also filter empty strings, if you want more control over what you filter you can pass a function instead of None):

您也可以使用filter(注意:这也将过滤空字符串,如果您想更好地控制过滤的内容,您可以传递一个函数而不是None):

clean = filter(None, lis)

There is always the itertoolsapproach if you want more efficient looping, but these basic approaches should work for most day to day cases.

如果您想要更高效的循环,总是有itertools方法,但这些基本方法应该适用于大多数日常情况。

回答by Volatility

You could easily remove all NoneTypeobjects from a list using a list comprehension:

您可以NoneType使用列表理解轻松地从列表中删除所有对象:

lis = [i for i in lis if i is not None]

回答by Thorsten Kranz

List comprehension, as other answers proposed or, for the sake of completeness:

列出理解,正如其他答案所提议的那样,或者为了完整起见:

clean = filter(lambda x: x is not None, lis)

If the list is huge, an iterator approach is superior:

如果列表很大,迭代器方法更好:

from itertools import ifilter
clean = ifilter(lambda x: x is not None, lis)

回答by jetpack_guy

For those who came here from Google

对于那些从谷歌来到这里的人

In Python3 you can implement this using .__ne__dunder method (or 'magic method' if you will):

在 Python3 中,您可以使用 .__ne__dunder 方法(或“魔术方法”,如果您愿意的话)来实现它:

>>> list1 = [0, 'foo', '', 512, None, 0, 'bar']
>>> list(filter(None.__ne__, list1))
[0, 'foo', '', 512, 0, 'bar']

This is how it works:

这是它的工作原理:

  • None.__ne__(None)--> False

  • None.__ne__(anything)--> NotImplemented

  • None.__ne__(None)--> 错误

  • None.__ne__(任何东西)--> 未实现

NotImplementedexeption effectively is True, e.g.:

NotImplemented有效的例外是True,例如:

>>> bool(None.__ne__('Something'))
True

As of the beginning of 2019, Python has no built-in function for filtering None values which avoids common pitfals with deleting zeroes, empty strings, etc.

截至 2019 年初,Python 没有用于过滤 None 值的内置函数,这避免了删除零、空字符串等常见的陷阱。