来自两个不同字典的对应键的值的所有可能差异

时间:2019-04-07 11:03:43

标签: python list dictionary

与两个不同字典的相应键相比,值可能存在的差异。

例外;如果差异大于1500且小于-1500

,则跳过相同索引的差异操作

我的字典:

dict_1 = {'A': [100, 200, 300], 'B': [500, 600, 700], 'C': [900, 1000,
 1100]}  
dict_2 = {'A': [150, 250, 350], 'B': [550, 650, 750], 'C':
 [950, 1050, 1150]}

要执行的操作:

For A
150 - 100 (skip this because of same index)
250 - 100 = 150
350 - 100 = 250

150 - 200 = -50
250 - 200 (skip this because of same index)
350 - 200 = 150

150 - 300 = -150
250 - 300 = -50
350 - 300 (skip this because of same index)

其他键也是如此。我只需要值的差异即可。

预期输出

150

250

-50

150

-150

-50

我的尝试:

 for value2 in dict_2.values():
     for  v2 in value2:
         for value1 in dict_1.values():
             for v1 in value1:
                 if -1500 <= int(v2) - int(v1) <= 1500:
                    if list.index(v2) == list.index(v1):
                        continue
                    writer.writerow([int(v2) - int(v1)]) 

2 个答案:

答案 0 :(得分:2)

使用itertools.product

from itertools import product

dict_1 = {'A': [100, 200, 300], 'B': [500, 600, 700], 'C': [900, 1000, 1100]}  
dict_2 = {'A': [150, 250, 350], 'B': [550, 650, 750], 'C': [950, 1050, 1150]}

for key, values2 in dict_2.items():
    for (i1, v1), (i2, v2) in product(enumerate(dict_1[key]), enumerate(values2)):
        if i1 == i2:
            continue

        diff = v2 - v1

        if abs(diff) > 1500:
            continue

        print('{}: {} - {} = {}'.format(key, v2, v1, diff))

输出:

A: 250 - 100 = 150
A: 350 - 100 = 250
A: 150 - 200 = -50
A: 350 - 200 = 150
A: 150 - 300 = -150
A: 250 - 300 = -50
B: 650 - 500 = 150
B: 750 - 500 = 250
B: 550 - 600 = -50
B: 750 - 600 = 150
B: 550 - 700 = -150
B: 650 - 700 = -50
C: 1050 - 900 = 150
C: 1150 - 900 = 250
C: 950 - 1000 = -50
C: 1150 - 1000 = 150
C: 950 - 1100 = -150
C: 1050 - 1100 = -50

答案 1 :(得分:1)

您可以尝试此操作,在同一键中遍历两个dict值,然后使用enumerate获取索引,并检查索引和边界:

def diff_in_dicts(dict_1, dict_2):
    for k in dict_1.keys() & dict_2.keys():
        for i, n1 in enumerate(dict_1[k]):
            for j, n2 in enumerate(dict_2[k]):
                if i != j and abs(n2 - n1) <= 1500:
                    # writer.writerow([int(n2) - int(n1)])
                    print(n2 - n1)

测试代码:

dict_1 = {'A': [100, 200, 300], 'B': [500, 600, 700], 'C': [900, 1000,
                                                                1100]}
dict_2 = {'A': [150, 250, 350], 'B': [550, 650, 750], 'C':
        [950, 1050, 1150]}

diff_in_dicts(dict_1, dict_2)

输出:

150
250
-50
150
-150
-50
150
...

希望对您有所帮助,如有其他问题,请发表评论。 :)