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

Python深度不确定的嵌套列表的类型注解该如何定义?

深度不确定的嵌套列表类型注解方案

对于元素为整数或任意深度嵌套同结构列表的场景,需要使用递归类型注解来定义,具体实现如下:

实现方式(Python 3.10+)

通过TypeVar定义一个递归引用自身的类型,代码示例:

from typing import TypeVar

# 定义递归类型:要么是int,要么是包含该类型的列表
NestedIntList = TypeVar('NestedIntList', bound='list[NestedIntList] | int')

# 示例函数使用该类型注解
def traverse_nested_list(data: NestedIntList) -> None:
    if isinstance(data, list):
        for item in data:
            traverse_nested_list(item)
    else:
        print(f"处理整数: {data}")

# 测试深度不确定的嵌套列表
sample_data = [[[1, 2]], 2, [1, [3, [3]]], 3, [2, [2]]]
traverse_nested_list(sample_data)

兼容更早Python版本

如果使用Python 3.9及以下版本,需要借助typing.ForwardRef来处理类型的前向引用:

from typing import TypeVar, ForwardRef, List

NestedIntList = TypeVar('NestedIntList', bound=ForwardRef('List[NestedIntList]') | int)
# 需在定义后解析前向引用
from typing import get_type_hints
get_type_hints(traverse_nested_list)

核心逻辑是让类型定义自身引用自身,从而覆盖任意层级的嵌套结构,完美匹配深度不确定的嵌套列表场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:27:47