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

如何对比两个dict的取值:length数组元素与对应threshold值的比较方法

实现方法

你可以遍历两个字典的公共键,对每个键对应的length列表元素逐一和同键的阈值比较,根据需求输出结果或者存储为新字典。

1. 遍历输出逐元素对比结果

length = {(0,0):[1,3], (0,1):[1,3,5,7], (1,1):[2,4,7], (1,2):[3,1,6]}
threshold = {(0,0):2, (0,1):4, (1,1):6, (1,2):3}

for key in length:
    # 跳过threshold中不存在的键
    if key not in threshold:
        continue
    thres = threshold[key]
    print(f"键{key}的对比结果:")
    for idx, num in enumerate(length[key]):
        # 可根据需求修改比较逻辑,示例为判断是否大于阈值
        res = num > thres
        print(f"第{idx+1}个元素{num} 对比 阈值{thres}:{res}")

运行输出示例:

键(0, 0)的对比结果:
第1个元素1 对比 阈值2:False
第2个元素3 对比 阈值2:True
键(0, 1)的对比结果:
第1个元素1 对比 阈值4:False
第2个元素3 对比 阈值4:False
第3个元素5 对比 阈值4:True
第4个元素7 对比 阈值4:True
键(1, 1)的对比结果:
第1个元素2 对比 阈值6:False
第2个元素4 对比 阈值6:False
第3个元素7 对比 阈值6:True
键(1, 2)的对比结果:
第1个元素3 对比 阈值3:False
第2个元素1 对比 阈值3:False
第3个元素6 对比 阈值3:True

2. 生成结果字典(批量存储对比结果)

如果不需要打印,直接把结果存为字典可以用推导式快速实现:

compare_res = {
    key: [num > threshold[key] for num in val]
    for key, val in length.items()
    if key in threshold
}
print(compare_res)

运行输出:

{(0, 0): [False, True], (0, 1): [False, False, True, True], (1, 1): [False, False, True], (1, 2): [False, False, True]}

如果需要调整比较规则,比如判断是否小于、大于等于阈值,直接修改列表推导式中的比较运算符即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:06:06