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

如何用Pydantic创建含最小长度为2的字符串子列表的包装类?

实现方案

你要的需求完全可以实现,下面提供两种常用的方法:

1. 嵌套conlist直接实现

Pydantic的conlist(约束列表)支持嵌套使用,刚好能满足你的需求——父列表允许为空,每个子列表必须包含至少2个字符串元素。

示例代码:

from pydantic import BaseModel, conlist

class StringListWrapper(BaseModel):
    # 父列表min_length=0允许空列表;子列表要求最少2个字符串元素
    data: conlist(conlist(str, min_length=2), min_length=0)

验证测试

  • 有效输入:
    # 空列表
    StringListWrapper(data=[])
    # 每个子列表长度≥2
    StringListWrapper(data=[["a", "b"], ["c", "d", "e"]])
    
  • 无效输入会触发验证错误:
    # 子列表为空
    StringListWrapper(data=[[]])  # 报错
    # 存在长度为1的子列表
    StringListWrapper(data=[["a"], ["b", "c"]])  # 报错
    

2. 使用typing.Annotated结合验证器

如果需要更灵活的自定义验证逻辑(比如后续要加其他规则),可以用Annotated搭配Pydantic的验证器实现:

示例代码:

from typing import Annotated, List
from pydantic import BaseModel, AfterValidator

def check_sublist_length(lists: List[List[str]]) -> List[List[str]]:
    for idx, sublist in enumerate(lists):
        if len(sublist) < 2:
            raise ValueError(f"第{idx+1}个子列表长度不足2,当前长度为{len(sublist)}")
    return lists

class StringListWrapper(BaseModel):
    data: Annotated[List[List[str]], AfterValidator(check_sublist_length)]

这种方式的优势是可以自定义错误提示信息,或者添加更多验证逻辑(比如检查子列表元素是否符合特定格式)。

总结

  • 嵌套conlist是最简洁的实现方式,适合仅需长度约束的场景;
  • Annotated+自定义验证器更灵活,适合复杂验证需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:43:19