有人可以帮我选择两把钥匙之间的最小值吗?例如,如果我有词典列表:
results = [
{
"model": "short",
"score": 34,
"alt_score": 1
},
{
"model": "med",
"score": 22,
"alt_score": 11
},
{
"model": "tall",
"score": 42,
"alt_score": 90
},
{
"model": "xtall",
"score": 83,
"alt_score": 15
},
]
我想选择score
OR alt_score
最小的字典。我知道如何找到具有最小score
或alt_score
的字典:
min(results, key=lambda x:x['alt_score'])
但我不确定如何一次看两个键。我需要类似的东西:
min(results, key=lambda x:x['score', 'alt_score])
或
min(results, key=lambda x:x['score'] or x:x['alt_score'])
结果应该返回:
{
"model": "short",
"score": 34,
"alt_score": 1
}
提前致谢!
答案 0 :(得分:6)
min(results, key=lambda x:min(x['score'], x['alt_score']))
Lambdas可以在其中包含几乎任何表达式,包括对min()
的内部调用,以获取项目score
或alt_score
中的较小者。
答案 1 :(得分:3)
你可以用这个:
min(results, key=lambda x: min(x['score'], x['alt_score']))
答案 2 :(得分:1)
min(results, key=lambda x:min(x['score'], x['alt_score']))
x需要引用内部min()比较的每个分数。
答案 3 :(得分:0)
results = [
{
"model": "short",
"score": 34,
"alt_score": 1
},
{
"model": "med",
"score": 22,
"alt_score": 11
},
{
"model": "tall",
"score": 42,
"alt_score": 90
},
{
"model": "xtall",
"score": 83,
"alt_score": 15
},
]
print(min(results, key=lambda x:min(x['score'],x['alt_score'])))