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

如何在Python中检查变量是否为List[List[str]]或List[str]类型?

如何检查Python中带泛型的列表类型

你遇到的问题是因为Python运行时会做类型擦除,type()只能拿到最基础的list类型,没法直接获取泛型参数(比如List[str]里的str)。要实现你要的精确类型检查,有两种可行思路:

方法一:用typing模块解析泛型类型

如果你的变量是通过泛型类型注解定义的(或用了保留泛型信息的方式),可以用get_origin和get_args函数解析泛型细节:

from typing import get_origin, get_args, List

def check_exact_type(var):
    var_type = type(var)
    # 先确认是列表类型
    if get_origin(var_type) != list:
        return None
    # 获取泛型参数
    args = get_args(var_type)
    # 匹配List[str]
    if len(args) == 1 and args[0] is str:
        return List[str]
    # 匹配List[List[str]]
    elif len(args) == 1:
        inner_type = args[0]
        if get_origin(inner_type) == list and get_args(inner_type) == (str,):
            return List[List[str]]
    return None

# 示例:仅当变量被明确标记泛型时有效
from typing import Annotated
var1: Annotated[List[str], "mark"] = ["a", "b"]
var2: Annotated[List[List[str]], "mark"] = [["a"], ["b"]]

if check_exact_type(var1) == List[str]:
    # do another thing
    pass
elif check_exact_type(var2) == List[List[str]]:
    # do something
    pass

注意:普通创建的列表(比如var = ["a"])运行时不会保留泛型信息,这种方法对这类变量无效。

方法二:直接检查元素实际类型(更实用)

实际开发中,我们通常不需要严格检查泛型类型定义,而是要确保列表元素符合预期。这种遍历检查的方式更可靠:

def is_list_of_str(var):
    if not isinstance(var, list):
        return False
    # 验证每个元素都是字符串
    return all(isinstance(item, str) for item in var)

def is_list_of_list_of_str(var):
    if not isinstance(var, list):
        return False
    # 验证每个元素都是字符串列表
    return all(is_list_of_str(item) for item in var)

# 直接使用判断逻辑
if is_list_of_list_of_str(var):
    # do something
    pass
elif is_list_of_str(var):
    # do another thing
    pass

这种方法不管变量有没有泛型注解,都能准确验证元素类型,是日常开发的首选方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 09:12:40