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

Python遍历列表报TypeError: 'NoneType' object is not subscriptable怎么解决

报错原因

你遇到的类型错误是因为new_list中存在None类型元素,None不支持下标取值操作p['src'],直接对其取值就会触发报错。

解决代码

遍历过程中新增过滤判断,跳过None元素,同时用更安全的方式提取属性即可:

for p in new_list:
    # 过滤None元素,同时判断元素支持属性获取
    if p is not None:
        # 用get方法提取src,不存在该属性时不会抛出异常
        src = p.get('src')
        if src:
            print(src)

如果你的列表中存储的是字典格式元素,可以调整判断逻辑适配:

for p in new_list:
    # 先判断元素是字典且存在src键再取值
    if isinstance(p, dict) and 'src' in p:
        print(p['src'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:54:09