评估字典中不同键的值 [英] Evaluating values within a dictionary for different keys

查看:166
本文介绍了评估字典中不同键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套字典,我想获取每个值之间的差异。

I have a nested dictionary to which I would like to obtain the differences between each value.

locsOne = {1:[100], 2:[200], 3:[250]}

只是例子)
我正在尝试对每个键应用一个abs( - )函数:value来获取每个键之间的距离,并创建一个具有结果的字典。我想要结果格式化如下:

(these values here are just examples) I'm attempting to apply a abs(-) function to each key:value to get the distance between each and create a dictionary with the results. How I'd like the results to be formatted would be:

locsTwo = {1:{2:100, 3:150}, 2:{1:100, 3:50}, 3:{1:150, 2: 50 }}

我目前的尝试是:

for i in range(len(listOne)):
    if abs(listOne[i] - listTwo[i]) >= 450:
        pass
    else:
        distances.append(abs(listOne[i] - listTwo[i]))

有如何做到这一点的损失。任何帮助将不胜感激。

Kind of at a loss on how to do this. Any help would be appreciated.

编辑:

我正在检查在循环中的差值大于450,所以不同于大于450的任何值都将丢弃/不包含在我们的结果集中。

I'm checking if the difference is greater that 450 in the loop so that any values that differ greater than 450 are discarded / not included in our result set.

推荐答案

locsOne = {1:[100], 2:[200], 3:[250]}
locsTwo = {}
for k1 in locsOne:
    v1 = locsOne[k1][0]
    locsTwo[k1] = {k2: abs(v1 - locsOne[k2][0]) for k2 in locsOne
                   if k1 != k2 and abs(v1 - locsOne[k2][0]) <= 450}
print(locsTwo)

输出:

{1: {2: 100, 3: 150}, 2: {1: 100, 3: 50}, 3: {1: 150, 2: 50}}

这篇关于评估字典中不同键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆