问题描述
我正在Python中使用Beautiful Soup从HTML文件中抓取一些数据.在某些情况下,Beautiful Soup会返回同时包含string
和NoneType
对象的列表.我想过滤掉所有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函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!