1 回答
TA貢獻1827條經驗 獲得超8個贊
假設您想要字典值之間的最小絕對差異,您可以執行以下操作:
data = [{
"acousticness": 0.0681,
"energy": 0.724,
"loudness": -5.941,
"tempo": 132.056,
"valence": 0.676
},
{
"acousticness": 0.2754,
"energy": 0.866,
"loudness": -7.874,
"tempo": 180.056,
"valence": 0.540
},
{
"acousticness": 0.0681,
"energy": 0.724,
"loudness": -5.941,
"tempo": 132.056,
"valence": 0.676
}]
target = {
"acousticness": 0.1382,
"energy": 0.7274,
"loudness": -5.8246,
"tempo": 122.6412,
"valence": 0.6153
}
def key(d, t=target):
return sum(abs(t[k] - v) for k, v in d.items())
result = min(data, key=key)
print(result)
輸出
{'tempo': 132.056, 'loudness': -5.941, 'acousticness': 0.0681, 'valence': 0.676, 'energy': 0.724}
答案的關鍵是使用min的key參數。請注意,可以調整此答案以適應多種接近度度量。例如,您可以更改鍵來計算字典值之間的歐幾里德距離:
import math
def key(d, t=target):
return math.sqrt(sum((t[k] - v)**2 for k, v in d.items())
添加回答
舉報
