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())
添加回答
举报