首页 > 解决方案 > 返回 None 类型列表而不是什么的函数

问题描述

我正在使用列表理解从现有列表中过滤掉一些单词,然后如果其长度大于三,则希望返回该列表。

我已经这样做了,但不是去 else 语句并且不返回任何它返回 None 值的东西。首先,为什么它返回一个 None 值,有没有办法不返回任何东西?下面的代码重新创建了这个输出。

new_list = ['have', 'to', 'deal', 'with', 'the', 'rat', 'can', 't', 'have', 'it']

def processing_text(tweetobj):
    filtered_words = [word for word in new_list if word not in stopwords.words('english')]
    if len(filtered_words) > 3:
        return (filtered_words)
    else:
        pass

print (processing_text(new_list))

标签: pythonpython-3.x

解决方案


我假设filtered_words在列表理解之后数组为空,因此该函数不返回任何内容(进入else子句并简单地通过)。因此,函数返回None,因此打印返回值显示None在这种情况下,None没有任何意义。

你的else条款是多余的:

def processing_text(tweetobj):
    filtered_words = [word for word in new_list if word not in stopwords.words('english')]
    if len(filtered_words) > 3:
        return (filtered_words)

>>> def foo():
...     1
... 
>>> x = foo()
>>> x
>>> x == None
True
>>> 

推荐阅读