1 回答
TA贡献1807条经验 获得超9个赞
尝试:
def sort_by_proximity(lst, value):
return sorted(lst, key=lambda x: abs(x['risk']['short'] - value))
对于给定的示例,像这样使用它:
lst = [
{'name': 'ZARA', 'risk': {'long': 3.9119195349019025, 'medium': 5, 'short': 4.485673554927903}},
{'name': 'SANTANDER', 'risk': {'long': 4.712942479560081, 'medium': 5, 'short': 4.348982243206375}},
{'name': 'BBC', 'risk': {'long': 5, 'medium': 5, 'short': 5}},
{'name': 'DISNEY', 'risk': {'long': 5, 'medium': 5, 'short': 5}},
{'name': 'BBVA', 'risk': {'long': 5, 'medium': 5, 'short': 5}},
{'name': 'IBEX35', 'risk': {'long': 4.8565761936412235, 'medium': 1.9216799766282, 'short': 1.3943451064412182}}
]
print(sort_by_proximity(lst, 3))
添加回答
举报