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

Python列表按连续值拆分子列表及matplotlib绘图问题

列表拆分逻辑错误原因及解决方案

错误原因

原有代码在使用for+enumerate遍历列表的同时删除列表元素,会导致遍历索引错位:删除第i个元素后,原i+1位置的元素会前移到i的位置,但for循环的索引会自动加1,直接跳过了该元素的匹配判断,因此最终只能得到两两拼接的错误结果。

正确实现方案

推荐使用新建结果列表的方式实现,无需修改正在遍历的对象,逻辑更稳定不易出错:

def split_list(input_list):
    # 处理空输入的边界情况
    if not input_list:
        return []
    # 初始化结果列表,放入第一个元素作为首个子列表
    result = [[input_list[0]]]
    # 从第二个元素开始遍历
    for num in input_list[1:]:
        # 当前元素和最后一个子列表的元素值相同,追加到子列表末尾
        if num == result[-1][0]:
            result[-1].append(num)
        # 元素值不同,新增一个子列表
        else:
            result.append([num])
    return result

调用该函数传入你的main_list即可得到目标输出:
[[5, 5, 5, 5, 5, 5], [0, 0, 0, 0], [5, 5, 5, 5, 5, 5], [0, 0], [5], [0, 0]]

配套绘图实现

按需求值为5的序列绘制红线、值为0的序列在固定y值处绘制蓝线的完整代码如下:

import matplotlib.pyplot as plt

def split_list(input_list):
    if not input_list:
        return []
    result = [[input_list[0]]]
    for num in input_list[1:]:
        if num == result[-1][0]:
            result[-1].append(num)
        else:
            result.append([num])
    return result

main_list = [5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 0, 0, 5, 0, 0]
x_axis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
splited_list = split_list(main_list)

current_x_idx = 0
fixed_y_for_zero = 0 # 0序列的固定y值,可自行修改
for sub_list in splited_list:
    sub_length = len(sub_list)
    x_segment = x_axis[current_x_idx:current_x_idx + sub_length]
    if sub_list[0] == 5:
        plt.plot(x_segment, [5]*sub_length, color="red", linewidth=2)
    else:
        plt.plot(x_segment, [fixed_y_for_zero]*sub_length, color="blue", linewidth=2)
    current_x_idx += sub_length

plt.xticks(x_axis)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:15:07