You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

列表推导式触发NoneType不可迭代TypeError报错如何解决

问题原因

报错的核心原因是description字段为空时,entry.get('description')会返回None,而in运算符要求右侧操作数为可迭代对象,None不属于可迭代对象,因此直接抛出TypeError: argument of type 'NoneType' is not iterable异常。

解决方案

方案1(最简推荐)

给dict.get()方法补充第二个默认返回空字符串的参数,空字符串属于合法可迭代对象,不会触发报错,且空字符串无法匹配任何搜索词,正好符合空description不命中搜索的业务逻辑。
修改后代码如下:

view['entries'] = [entry for entry in view['entries'] if qs in entry.get('name') or qs in entry.get('description', '')]

方案2(显式判空)

如果需要更明确的逻辑区分,也可以先判断description是否为None再执行搜索判断:

view['entries'] = [entry for entry in view['entries'] if qs in entry.get('name') or (entry.get('description') is not None and qs in entry.get('description'))]

内容的提问来源于stack exchange,提问作者akromx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 14:36:06