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

Python如何计算列表元素差值并保留元素原始索引位置

实现方案

核心思路是排序时保留元素对应的原索引,识别到符合差值要求的元素对后,直接标记对应原索引的位置即可,同时要注意符合条件的相邻两个元素都需要标记,而不是只标记后一个。

方法1:NumPy 实现

import numpy as np

x = np.array([0.2, 0.1, 0.3, 0.100000001, 0.200000002])
threshold = 1e-5

# 按值排序,同时保留原索引
sorted_idx = np.argsort(x)
sorted_vals = x[sorted_idx]

# 筛选差值小于阈值的相邻位置
match_pos = np.where(np.diff(sorted_vals) < threshold)[0]

# 初始化结果数组,标记符合条件的原索引
res = np.zeros(len(x), dtype=bool)
for pos in match_pos:
    res[sorted_idx[pos]] = True
    res[sorted_idx[pos+1]] = True

print(res.tolist())

输出结果:[True, True, False, True, True]

方法2:纯Python实现

不需要依赖第三方库,直接用原生语法实现:

x = [0.2, 0.1, 0.3, 0.100000001, 0.200000002]
threshold = 1e-5

# 打包元素和原索引后按值排序
sorted_with_index = sorted(enumerate(x), key=lambda item: item[1])
res = [False] * len(x)

for i in range(len(sorted_with_index) - 1):
    curr_val, next_val = sorted_with_index[i][1], sorted_with_index[i+1][1]
    if abs(next_val - curr_val) < threshold:
        # 同时标记相邻两个元素对应的原索引
        res[sorted_with_index[i][0]] = True
        res[sorted_with_index[i+1][0]] = True

print(res)

输出结果同样为[True, True, False, True, True]


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:27:05