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

如何根据嵌套列表首元素条件实现分组嵌套列表

解决方案:按首元素0分组嵌套列表

问题说明

给定输入列表:

[[0, 78], [0, 118], [1, 198], [1, 78], [0, 118], [0, 198], [1, 434], [1, 514], [1, 434]]

需要按以下规则分组:每遇到首元素为0的子列表时,创建新分组,包含该子列表及后续所有子列表,直到下一个首元素为0的子列表出现。最终期望输出:

[[[0, 78], [0, 118], [1, 198], [1, 78]], [[0, 118], [0, 198], [1, 434], [1, 514], [1, 434]]]

实现代码

input_list = [[0, 78], [0, 118], [1, 198], [1, 78], [0, 118], [0, 198], [1, 434], [1, 514], [1, 434]]
result = []
current_group = []

for item in input_list:
    if item[0] == 0:
        # 若当前分组已有内容,先存入结果集
        if current_group:
            result.append(current_group)
            current_group = []
        current_group.append(item)
    else:
        current_group.append(item)
# 加入最后一组未处理的内容
if current_group:
    result.append(current_group)

print(result)

逻辑解释

  1. 初始化两个容器:result用来存储最终的分组结果,current_group用来暂存当前正在构建的分组
  2. 遍历输入列表的每个子元素:
    • 当遇到首元素为0的子列表时,先检查current_group是否有内容:如果有,说明上一个分组已经到了结束节点,将其存入result后重置current_group,再把当前0开头的子列表加入current_group
    • 遇到首元素为1的子列表,直接追加到current_group中
  3. 遍历结束后,将最后一个未存入result的分组添加进去,避免遗漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:33:17