如何根据嵌套列表首元素条件实现分组嵌套列表
解决方案:按首元素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)
逻辑解释
- 初始化两个容器:
result用来存储最终的分组结果,current_group用来暂存当前正在构建的分组 - 遍历输入列表的每个子元素:
- 当遇到首元素为0的子列表时,先检查
current_group是否有内容:如果有,说明上一个分组已经到了结束节点,将其存入result后重置current_group,再把当前0开头的子列表加入current_group - 遇到首元素为1的子列表,直接追加到
current_group中
- 当遇到首元素为0的子列表时,先检查
- 遍历结束后,将最后一个未存入
result的分组添加进去,避免遗漏
内容的提问来源于stack exchange,提问作者mod13
相关产品推荐
相关产品推荐

