索引列表差值处理:保留首个重复1并跳过后续项的代码问题
差值列表规则化处理实现方案
需求明确
- 原始索引列表:
index = [461, 470, 479, 488, 489, 490, 491, 492, 520, 521, 522, 531, 540] - 当前差值列表:
difference = [9, 9, 9, 1, 1, 1, 1, 28, 1, 1, 9, 9] - 预期输出列表:
[461, 9, 9, 9, 1, 1, 1, 1, 28, 1, 1, 9, 9, 540] - 处理规则:
- 差值为
9时直接保留 - 差值为
1时,保留当前及后续连续的1(最多5个),处理完后跳过剩余连续的1 - 其他数值(如
28)直接保留 - 最终需在列表首尾分别加入原始索引的第一个和最后一个元素
- 差值为
代码实现
index = [461, 470, 479, 488, 489, 490, 491, 492, 520, 521, 522, 531, 540] difference = [9, 9, 9, 1, 1, 1, 1, 28, 1, 1, 9, 9] result = [index[0]] # 先加入第一个索引值 i = 0 diff_len = len(difference) while i < diff_len: current_diff = difference[i] if current_diff == 9: result.append(current_diff) i += 1 elif current_diff == 1: # 处理连续的1,最多保留5个 take_count = 0 while i < diff_len and difference[i] == 1 and take_count < 5: result.append(difference[i]) i += 1 take_count += 1 # 跳过剩余连续的1(如果有的话) while i < diff_len and difference[i] == 1: i += 1 else: # 其他数值直接保留 result.append(current_diff) i += 1 result.append(index[-1]) # 加入最后一个索引值 print(result)
代码说明
- 用
while循环手动控制遍历索引,避开for循环自动递增的限制,解决了之前用break终止整个循环的问题 - 遇到连续
1时,先按规则保留最多5个,再跳过剩余的连续1,完成当前块处理后继续遍历后续元素 - 首尾分别加入原始索引的首尾元素,确保输出格式完全符合预期
输出验证
运行代码后会得到预期结果:
[461, 9, 9, 9, 1, 1, 1, 1, 28, 1, 1, 9, 9, 540]
内容的提问来源于stack exchange,提问作者user6803504
相关产品推荐
相关产品推荐

