我是 python 新手。在 Python 中,我想比較兩個字典串列
下面是我要比較的兩個字典串列,鍵是“zrepcode”,id是數字“1”、“3”和“4”...
代碼片段如下:
List1 = [{"3":[{"period":"P13","value":10,"year":2022}],"zrepcode":"55"},{"1":[{"period":"P10","value":5,"year":2023}],"zrepcode":"55"}]
List2 = [{"1":[{"period":"P1","value":10,"year":2023},{"period":"P2","value":5,"year":2023}],"zrepcode":"55"},{"3":[{"period":"P1","value":4,"year":2023},{"period":"P2","value":7,"year":2023}],"zrepcode":"55"},{"4":[{"period":"P1","value":10,"year":2023}],"zrepcode":"55"}]
比較之后,我們需要來自 list2 的唯一字典串列。
res = [{"4":[{"period":"P1","value":10,"year":2023}],"zrepcode":"55"}]
這是預期的輸出,現在我不知道我是如何得到這個的。
uj5u.com熱心網友回復:
您可以使用串列推導來過濾串列。
[x for x in list if condition]
和 any() 查看串列是否有任何匹配條件的元素
any(condition for y in list)
或者在你的情況下,因為你想要那些不存在于另一個
[x for x in list2 if not any(your_condition for y in list1)]
要檢查兩個元素是否具有相同的 zrepcode 值,您可以像這樣比較它們
x['zrepcode'] == y['zrepcode']
由于您的另一個比較點是鍵,并且每個鍵只有兩個鍵,因此您可以比較兩者的鍵
x.keys() == y.keys()
結合一切
[x for x in list2 if not any(x['zrepcode'] == y['zrepcode'] and x.keys() == y.keys() for y in list1)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496872.html
標籤:Python python-3.x 列表 排序 字典
上一篇:我想按字典中元組的第一個元素排序
