斯蒂芬大帝
假设您想要字典值之间的最小绝对差异,您可以执行以下操作: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 mathdef key(d, t=target): return math.sqrt(sum((t[k] - v)**2 for k, v in d.items())