如何将一维列表中重复的0.02序列替换为其后的等长非重复数值序列
连续重复0.02段替换实现方法
实现思路
- 首先识别数组中所有连续为0.02的片段,记录每个片段的起始位置和长度(注意浮点数比较需处理精度问题,避免计算误差导致识别失效)
- 对每个识别到的0.02片段,取该片段结束位置之后长度相等的子序列,直接替换原0.02片段即可
代码实现
Numpy版本(适合超长数组,向量化操作效率更高)
import numpy as np # 输入数组 arr = np.array([0.24, 0.02, 0.02, 0.02, 5, 7, 9, 8.4, 97, 0.56, 34, 0.45, 0.02, 0.02, 0.02, 0.02, 0.02, 0.11, 12, 0.16, 19, 23, 27, 32, 37, 45, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 18, 24, 34, 45, 0.65, 68, 53, 48, 98, 78, 564, 343, 3534, 3435, 435, 131, 2435354, 45456, 232]) # 标记所有值为0.02的位置 mask = np.isclose(arr, 0.02) # 计算mask的差分,识别0.02段的起止位置 diff = np.diff(mask.astype(int)) starts = np.where(diff == 1)[0] + 1 ends = np.where(diff == -1)[0] # 处理边界情况:数组开头就是0.02 if mask[0]: starts = np.insert(starts, 0, 0) # 处理边界情况:数组结尾是0.02,若后续没有足够元素可按需调整逻辑 if mask[-1]: ends = np.append(ends, len(arr)-1) # 逐段替换 for s, e in zip(starts, ends): seg_len = e - s + 1 arr[s:e+1] = arr[e+1 : e+1 + seg_len] # 转换为列表输出 print(arr.tolist())
纯Python列表版本(无需依赖第三方库)
my_list = [0.24, 0.02, 0.02, 0.02, 5, 7, 9, 8.4, 97, 0.56, 34, 0.45, 0.02, 0.02, 0.02, 0.02, 0.02, 0.11, 12, 0.16, 19, 23, 27, 32, 37, 45, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 18, 24, 34, 45, 0.65, 68, 53, 48, 98, 78, 564, 343, 3534, 3435, 435, 131, 2435354, 45456, 232] res = [] idx = 0 list_len = len(my_list) float_tolerance = 1e-9 while idx < list_len: # 识别连续0.02段 if abs(my_list[idx] - 0.02) < float_tolerance: start_idx = idx while idx < list_len and abs(my_list[idx] - 0.02) < float_tolerance: idx += 1 seg_length = idx - start_idx # 拼接后续等长序列 res.extend(my_list[idx:idx+seg_length]) else: res.append(my_list[idx]) idx += 1 print(res)
运行上述任意代码,均可得到你给出的预期输出结果。
内容的提问来源于stack exchange,提问作者Bluee Skyy
相关产品推荐
相关产品推荐

