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

如何在Python中为不规则嵌套列表头部填充指定值?

解决方案

核心逻辑是:对每个第二层子列表,计算需要填充的[-10,-10,-10]数量(目标长度5减去原列表长度),再将填充列表拼接到原列表头部即可。

方法1:列表推导式(简洁高效)

original_list = [
    [[1,2,3], [1,2,3], [1,2,3]],
    [[1,2,3], [1,2,3]],
    [[1,2,3], [1,2,3], [1,2,3], [1,2,3]],
    # 可添加更多子列表
]
fill_item = [-10, -10, -10]
target_len = 5

processed_list = [
    [fill_item] * (target_len - len(sublist)) + sublist 
    for sublist in original_list
]

方法2:普通循环(新手友好,步骤清晰)

original_list = [
    [[1,2,3], [1,2,3], [1,2,3]],
    [[1,2,3], [1,2,3]],
    [[1,2,3], [1,2,3], [1,2,3], [1,2,3]],
    # 可添加更多子列表
]
fill_item = [-10, -10, -10]
target_len = 5

processed_list = []
for sublist in original_list:
    # 计算需要填充的个数
    fill_count = target_len - len(sublist)
    # 拼接填充列表与原列表
    new_sublist = [fill_item] * fill_count + sublist
    processed_list.append(new_sublist)

验证结果

运行代码后,processed_list会生成符合要求的结构:

# 输出示例
[
    [[-10,-10,-10], [-10,-10,-10], [1,2,3], [1,2,3], [1,2,3]],
    [[-10,-10,-10], [-10,-10,-10], [-10,-10,-10], [1,2,3], [1,2,3]],
    [[-10,-10,-10], [1,2,3], [1,2,3], [1,2,3], [1,2,3]]
]

补充说明

  • 如果后续需要修改填充的元素,建议用[fill_item.copy() for _ in range(fill_count)]代替[fill_item] * fill_count,避免因列表引用问题导致修改一个填充项时所有填充项同步变化。
  • 若原第二层子列表长度可能超过5,可将fill_count改为max(target_len - len(sublist), 0),确保填充数非负,避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:10:05