比较2个具有随机函数的不同词典

时间:2016-10-02 16:22:15

标签: python

所以,我在这里想要实现的是采用2个词典,将两个词典的值放在同一个词组中#34; spot"并能够应用任何功能。这是一些伪代码的例子:

If f(a, b) returns a + b
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
then function(d1, d2) returns ({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})
If f(a, b) returns a > b
d1 = {1:30, 2:20, 3:30}
d2 = {1:40, 2:50, 3:60}
then function(d1, d2) returns ({1: False, 2: False, 3: False}, {})

2 个答案:

答案 0 :(得分:0)

虽然可能有更有效的方法来实现您的目标,但我使用信息here来创建以下功能:

def f1(a,b):
    return a+b

def f2(a,b):
    return a>b

def function2(d1,d2):
    out1 = {}
    out2 = {}
    #use the set operations to take the common keys
    commons = set(set(d1) & set(d2))
    for i in commons:
        out1[i] = d1[i] > d2[i]
    #all the non-common keys go to out2
    for i in d1:
        if i not in commons:
            out2[i] = d1[i]
    for i in d2:
        if i not in commons:
            out2[i] = d2[i]
    return (out1,out2)

def function1(d1,d2):
    out1 = {}
    out2 = {}
    #use the set operations to take the common keys
    commons = set(set(d1) & set(d2))
    for i in commons: out1[i] = f1(d1[i],d2[i])
    #all the non-common keys go to out2
    for i in d1:
        if i not in commons:
            out2[i] = d1[i] 
    for i in d2:
        if i not in commons:
            out2[i] = d2[i]
    return (out1,out2) 

def main():

    d1 = {1:30, 2:20, 3:30, 5:80}
    d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
    d1,d2 = function1(d1,d2)
    for i in d1:print(i,d1[i])
    print('\n')
    for i in d2:print(i,d2[i])

    print('\n\n')

    d1 = {1:30, 2:20, 3:30}
    d2 = {1:40, 2:50, 3:60}
    d1,d2 = function2(d1,d2)
    for i in d1:print(i,d1[i])
    print('\n')
    for i in d2:print(i,d2[i])



if __name__ == '__main__':
    main()

我尽量让我的代码尽可能清晰。我希望它有所帮助。

答案 1 :(得分:0)

首先找到两个字典的交集和联合(作为集合) 交叉点用于元组的第一项 差异用于元组的第二项。

仿函数是使用交集值中的键对字典项执行的操作。这是第一个元组项中使用的最终结果。

要获得第二个元组的最终结果,找到d1和d2的合并字典,然后仅使用差异中的键返回字典键值

def func(d1, d2, functor):
    s_intersection = set(d1) & set(d2)
    s_difference = set(d1) ^ set(d2)
    merged = d1.copy()
    merged.update(d2)
    return {k: functor(d1[k], d2[k]) for k in s_intersection}, {k: merged[k] for k in s_difference}

d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
print func(d1, d2, lambda x, y: x+y)

d1 = {1:30, 2:20, 3:30}
d2 = {1:40, 2:50, 3:60}
print func(d1, d2, lambda x, y: x>y)
相关问题