如何实现不超长度限制的路径构建函数:优先保留指定字段及最多3个表演者
路径生成函数实现方案
需求
我拥有title、date、performers(表演者)、tags等字段,需要编写一个函数,接收这些字段后生成不超过指定长度限制的路径,要求:
- 最多保留3个表演者
- 尽可能多地包含标签
- 按指定优先级顺序添加字段,路径长度超限则舍弃后续字段
示例数据、模板及代码实现
# 示例数据 d = { "title": "标题", "date": "2020-01-01", "performers": ["表演者1", "表演者2", "表演者3", "表演者4"], "studio": "制作工作室", "tags": ["标签1", "标签2"], } # 字段添加优先级顺序:超限则停止添加后续字段 order_fields = ["date", "performers", "studio", "tags"] # 路径模板,占位符对应字段名 template = "{studio} {date} {performers} {title} {tags}" def build_path(d: dict, template: str, order_fields: list, max_length: int = 255) -> str: # 处理表演者字段:最多保留前3个 if "performers" in d and isinstance(d["performers"], list): d["performers"] = ", ".join(d["performers"][:3]) # 按优先级替换模板占位符,超限则终止 for field in order_fields: if field not in d: continue # 预计算替换后的长度,超过限制则停止 temp_template = template.replace(f"{{{field}}}", d[field]) if len(temp_template) > max_length: break template = temp_template # 清理未被替换的占位符 for field in order_fields: template = template.replace(f" {{{field}}}", "") return template def test_build_path(): global d, template, order_fields # 不同长度限制下的测试验证 assert build_path(d, template, order_fields, max_length=5) == "标题" assert build_path(d, template, order_fields, max_length=16) == "2020-01-01 标题" assert build_path(d, template, order_fields, max_length=36) == "2020-01-01 表演者1, 表演者2, 表演者3 标题" assert build_path(d, template, order_fields, max_length=43) == "制作工作室 2020-01-01 表演者1, 表演者2, 表演者3 标题" assert build_path(d, template, order_fields, max_length=48) == "制作工作室 2020-01-01 表演者1, 表演者2, 表演者3 标题 标签1" assert build_path(d, template, order_fields) == "制作工作室 2020-01-01 表演者1, 表演者2, 表演者3 标题 标签1, 标签2"
代码说明
- 表演者字段处理:提前截取前3个表演者,用逗号拼接成字符串,满足最多3个的要求
- 优先级替换逻辑:按
order_fields顺序依次替换模板占位符,每次替换前检查长度,超过限制则停止后续字段添加 - 占位符清理:移除所有未被替换的字段占位符,保证路径格式整洁
- 测试覆盖:包含不同长度限制场景,验证函数输出符合预期
内容的提问来源于stack exchange,提问作者user19924240
相关产品推荐
相关产品推荐

