簡體   English   中英

在字典列表中找到所有相同的鍵並找出它們的值之間的差異

[英]find all the same keys in a list of dicts and find the difference between their values

我有一個練習,我得到兩個或更多稀疏矩陣,我需要找到它們之間的區別。 輸入是一個字典列表,輸出是具有差異的字典:

輸入: diff_sparse_matrices([{(1, 3): 2, (2, 7): 1}, {(1, 3): 6}])
輸出: {(1, 3): -4, (2, 7): 1}

def diff_sparse_matrices(lst):
    new_dict = {}
    for d in lst :
        for key in d.keys() :

這就是我能想到的。 我該如何編寫這段代碼?

  • 我不能使用 numpy
  • 我不能使用集合

如果鍵的值為 0,我還需要刪除該項目,所以

輸入: diff_sparse_matrices([{(1, 3): 2, (2, 7): 1}, {(1, 3): 2}])
輸出: {(2, 7): 1}

我不知道為什么,但如果輸入是

[{(1, 3): 2, (2, 7): 1}, {(1, 3): 6, (9,10): 7}, {(2,7): 0.5, (4,2): 10}]

輸出是

{(1, 3): -4, (2, 7): 0.5, (9, 10): -7, (4,2): -10}

請注意,它是 - 7 和 -10 而不是 7 和 10

你可以用dict.get()試試這個:

lst_dct = [{(1, 3): 2, (2, 7): 1}, {(1, 3): 6, (9,10): 7}, {(2,7): 0.5, (4,2): 10}]

res = {}
for ld in lst_dct:
    for k,v in ld.items():
        res[k] = -v - res.get(k,0)
        
print(res)    

輸出:

{(1, 3): -4, (2, 7): 0.5, (9, 10): -7, (4, 2): -10}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM