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

Python 3.8定义Matrix类型别名出现TypeError错误如何解决?

修复Python 3.8中list[list[int]]的TypeError错误

在Python 3.8中,原生list类型不支持下标式的泛型注解语法(比如list[list[int]]),即便导入from __future__ import annotations也无法解决——因为这个导入仅延迟解析函数/类的注解字符串,而你是直接在赋值语句中尝试对list做下标操作,这会触发运行时错误。

以下是两种可行的修复方案:

  • 方案一:使用typing.List替代原生list
    Python 3.8的typing模块提供了支持泛型的List类型,可直接用来定义类型别名:

    from typing import List
    Matrix = List[List[int]]
    
  • 方案二:升级到Python 3.9及以上版本
    从Python 3.9开始(PEP 585),原生容器类型(如list、dict)开始支持泛型注解语法,你的原始代码可以直接正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:27:34