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

如何从字典值的数值列表中提取连续差值小于40的后项数值

需求实现方案

实现逻辑

  • 遍历字典中所有存储的数值列表
  • 对每个列表,从第二个元素开始依次和前一个相邻元素计算差值
  • 若差值小于40,就将当前的后一个元素存入结果汇总列表
  • 若需要兼容降序排列的列表,可以把差值计算替换为绝对值计算

代码实现

def collect_valid_nums(input_dict: dict) -> list:
    res = []
    for num_list in input_dict.values():
        # 长度小于2的列表没有相邻元素,直接跳过
        if len(num_list) < 2:
            continue
        for idx in range(1, len(num_list)):
            # 如需判断绝对差值,改为 abs(num_list[idx] - num_list[idx-1]) < 40即可
            if num_list[idx] - num_list[idx-1] < 40:
                res.append(num_list[idx])
    return res

测试示例

# 代入示例字典测试
test_data = {0: [41, 42, 183, 186, 471, 493, 639, 642, 732, 734], 1: [477, 489, 490]}
print(collect_valid_nums(test_data))

输出结果:[42, 186, 493, 642, 734, 489, 490]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:18:04