python - 返回 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))
解决方案
我假设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
>>>
推荐阅读
- javascript - 在 useEffect 运行后删除事件侦听器导致 scrollIntoView() 永远不会关闭?
- javascript - “TypeError:曲线不是函数。(在'curve(buffer = path())'中,'curve'未定义)”在d3.js.v4中
- javascript - OAuth2 和 angular-auth2-oidc 库的问题 - PKCE 代码流
- c++ - 在 BST 中插入一个具有全局根的节点
- python - 如何从 DataFrame 创建 HTML 表格
- json - Oracle 将所有键/值转换为行
- python - 如何导出变量形式 __init__ 并在其他函数中使用
- c++ - 将线程重定向到另一个函数
- electron - 窗口没有收到来自 IpcRenderer 的消息
- javascript - 如何及时添加前导零?