2016-10-02 46 views
1

所以,我想在這裏實現的是採取2個字典,採取在同一個「點」的兩個字典的值,並能夠應用任何功能。下面是一些僞代碼的例子:比較兩個不同的字典與隨機函數

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}, {}) 
+1

究竟什麼是你的問題只返回與鍵的字典鍵值?請查看[FAQ](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/help/how-to-ask)。 –

+0

看看這篇文章http://stackoverflow.com/questions/10461531/merge-and-sum-of-two-dictionaries – AlvaroP

+0

我不知道如何設置一個函數,比較後將返回值2個字典。你將不得不使用for循環並在使用返回函數之後?對於不問這個問題,我表示歉意,我對此很陌生。 – Alex

回答

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() 

我試圖讓我的代碼儘可能清楚。我希望它有幫助。

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)