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

如何在Python中平滑数值列表?含可参数化扩展需求

问题描述

给定整数列表(示例如下):

[0, 0, 1, 0, 1, 0, 0, 2, 1, 1, 1, 2, 1]

需要对其进行平滑处理:从左到右遍历序列,当某个中间元素的左侧连续n个元素、右侧连续n个元素的值完全相同,且该值与当前中间元素不同时,将中间元素替换为这个相同值。默认n=1(即前后各1个相同值),处理后示例结果为:

[0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1]

额外需求:支持参数化配置n的值,比如指定n=2时,需前后各连续2个相同值才触发替换。

解决方案

实现思路

  1. 先复制原列表,避免修改原始数据;
  2. 遍历所有符合条件的中间位置(跳过首尾无法提供足够左右元素的位置);
  3. 对每个位置,验证左侧连续n个元素是否为同一值,右侧连续n个元素是否为同一值;
  4. 若左右侧的相同值一致,且与当前元素不同,则替换当前元素;
  5. 从左到右处理,替换后的元素会作为后续位置的左侧参考,完全匹配需求中的处理顺序。

代码实现

def smooth_sequence(seq, window_size=1):
    # 处理空列表或长度不足的情况(无法找到满足条件的中间元素)
    if len(seq) < 2 * window_size + 1:
        return seq.copy()
    
    smoothed = seq.copy()
    seq_length = len(smoothed)
    
    # 遍历所有可检查的中间位置
    for idx in range(window_size, seq_length - window_size):
        # 验证左侧连续window_size个元素是否一致
        left_target = smoothed[idx - window_size]
        left_match = all(smoothed[idx - k] == left_target for k in range(1, window_size + 1))
        if not left_match:
            continue
        
        # 验证右侧连续window_size个元素是否一致
        right_target = smoothed[idx + window_size]
        right_match = all(smoothed[idx + k] == right_target for k in range(1, window_size + 1))
        if not right_match:
            continue
        
        # 左右值相同且与当前值不同时执行替换
        if left_target == right_target and smoothed[idx] != left_target:
            smoothed[idx] = left_target
    
    return smoothed

# 测试示例输入
original_list = [0, 0, 1, 0, 1, 0, 0, 2, 1, 1, 1, 2, 1]
processed_list = smooth_sequence(original_list)
print(processed_list)  # 输出: [0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1]

# 测试window_size=2的场景
test_sequence = [0, 0, 0, 1, 0, 0, 0]
print(smooth_sequence(test_sequence, window_size=2))  # 输出: [0, 0, 0, 0, 0, 0, 0]

代码说明

  • window_size:核心参数,指定触发替换所需的前后连续相同元素数量,默认值为1;
  • 边界处理:当列表长度小于2*window_size +1时,直接返回原列表拷贝,因为不存在能满足前后各window_size个元素的中间位置;
  • 遍历逻辑:只处理有效中间位置,避免索引越界;
  • 顺序处理:从左到右遍历,修改后的元素会影响后续判断,严格符合需求中的处理顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:26:01