我想比較兩個字典串列,如果字典匹配,則將鍵/值 True 添加到第二個字典串列;如果它們不匹配,則將鍵/值 False 添加到第二個字典串列中。
當前代碼:
list_dict1 = [{'animal': 'Dog', 'age': '3'}, {'animal':'Horse', 'age': '6'}]
list_dict2 = [{'animal': 'Dog', 'age': '3'}, {'animal':'Horse', 'age': '8'}]
for d1 in list_dict1:
for d2 in list_dict2:
if d1 == d2:
d2['match'] = True
else:
d2['match'] = False
電流輸出:
list_dict2 = [{'animal': 'Dog', 'age': '3', 'match': False},
{'animal': 'Horse', 'age': '8', 'match': False}]
期望的輸出:
list_dict2 = [{'animal': 'Dog', 'age': '3', 'match': True},
{'animal': 'Horse', 'age': '8', 'match': False}]
我假設這不起作用的原因是因為在每次迭代中都會list_dict2發生變化,這意味著回圈后面沒有匹配,因為我正在添加一個新值。有什么想法可以繼續嗎?
uj5u.com熱心網友回復:
您的解決方案的問題是您再次覆寫了結果。
我會檢查第二個串列并檢查每個專案是否在第一個串列中,如下所示:
for d1 in list_dict2:
if d1 in list_dict1:
d1['match'] = True
else:
d1['match'] = False
print(list_dict2)
輸出:
[{'animal': 'Dog', 'age': '3', 'match': True},
{'animal': 'Horse', 'age': '8', 'match': False}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441346.html
標籤:Python python-3.x 列表 字典
上一篇:地圖中的常規輸出
