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

Cadence仿真PWL电压脚本:移除连续重复元素中间项需求

处理PWL仿真数据的连续重复元素保留逻辑

需求说明

需要处理用于Cadence PWL电压仿真的两个对应列表:

  • 以y_list为参考,当其中出现连续重复元素超过2个时,仅保留该重复段的首尾2个元素
  • 同步对x_list执行相同的索引过滤,保留对应位置的首尾元素

示例:

  • 原列表:x_list = [0, 1, 2, 3, 4, 5],y_list = [0, 2, 2, 2, 2, 4]
  • 处理后:new_x_list = [0, 1, 4, 5],new_y_list = [0, 2, 2, 4]
    (移除了(2,2)和(3,2)两组对应对)

解决方案

直接遍历原列表并构建新列表是最稳妥的方式(避免在遍历中修改原列表导致的索引混乱),以下是Python实现代码:

def filter_consecutive_duplicates(x_list, y_list):
    if not x_list or not y_list or len(x_list) != len(y_list):
        return [], []
    
    new_x = [x_list[0]]
    new_y = [y_list[0]]
    
    # 跟踪当前连续重复的元素和计数
    current_val = y_list[0]
    consecutive_count = 1
    # 记录当前重复段的起始索引(用于后续取首尾)
    start_idx = 0
    
    for i in range(1, len(y_list)):
        if y_list[i] == current_val:
            consecutive_count += 1
        else:
            # 遇到新元素,处理之前的重复段
            if consecutive_count > 2:
                # 重复段超过2个,只加末尾元素
                new_x.append(x_list[i-1])
                new_y.append(current_val)
            else:
                # 重复段<=2个,把中间的元素补上
                for j in range(start_idx + 1, i):
                    new_x.append(x_list[j])
                    new_y.append(y_list[j])
            # 更新跟踪变量
            current_val = y_list[i]
            consecutive_count = 1
            start_idx = i
            # 加入当前新元素
            new_x.append(x_list[i])
            new_y.append(y_list[i])
    
    # 处理列表末尾的重复段
    if consecutive_count > 2:
        new_x.append(x_list[-1])
        new_y.append(current_val)
    else:
        for j in range(start_idx + 1, len(y_list)):
            new_x.append(x_list[j])
            new_y.append(y_list[j])
    
    return new_x, new_y

# 测试示例
x_list = [0, 1, 2, 3, 4, 5]
y_list = [0, 2, 2, 2, 2, 4]
new_x, new_y = filter_consecutive_duplicates(x_list, y_list)
print("new_x_list:", new_x)  # 输出: [0, 1, 4, 5]
print("new_y_list:", new_y)  # 输出: [0, 2, 2, 4]

代码逻辑说明

  • 先做参数校验:确保两个列表非空且长度一致
  • 初始化新列表,先加入第一个元素
  • 遍历过程中跟踪当前重复值、计数和起始索引:
    • 遇到相同元素时,只增加计数
    • 遇到不同元素时,根据之前的重复长度决定是只加末尾元素,还是补全中间所有元素
  • 最后单独处理列表末尾的重复段(避免循环结束后遗漏)

这样既不会因为修改原列表导致索引错乱,也能完美同步两个列表的过滤逻辑。

内容的提问来源于stack exchange,提问作者Victor S. P. Carpes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:33:24