从字典中找到加权最小值和最大值键的Pythonic方法
我使用的数据集与此类似:从字典中找到加权最小值和最大值键的Pythonic方法,python,dictionary,Python,Dictionary,我使用的数据集与此类似: animals = { "antelope": { "latin": "Hippotragus equinus", "cool_factor": 1, "popularity": 6 }, "ostrich": { "latin": "Struthio camelus
animals = {
"antelope": {
"latin": "Hippotragus equinus",
"cool_factor": 1,
"popularity": 6
},
"ostrich": {
"latin": "Struthio camelus",
"cool_factor": 3,
"popularity": 3
},
"echidna": {
"latin": "Tachyglossus aculeatus",
"cool_factor": 5,
"popularity": 1
}
}
我想做的是找到受欢迎程度影响的“最不酷”和“最酷”的动物,比如:
> min_cool_weighted(animals)
"echidna"
> max_cool_weighted(animals)
"ostrich"
我首先想到的解决方案是创建3个数组(keys
、cool\u factors
、和popularity
),遍历字典,将所有值推到3个数组中,然后创建第四个数组,每个数组的值都是加权[i]=cool\u factors[i]*流行度[i]
,然后取最小/最大值并从密钥数组中获取相应的密钥。然而,这看起来并不是很像蟒蛇
有更好、更具表现力的方式吗?而且应该足够了
min(animals, key=lambda x: animals[x]["cool_factor"]*animals[x]["popularity"])
'echidna'
max(animals, key=lambda x: animals[x]["cool_factor"]*animals[x]["popularity"])
'ostrich'
您可以使用
sorted
最小值:
最大值:
sorted(animals.iteritems(),
key=lambda x:x[1]['cool_factor']*x[1]['popularity'])[0][0]
sorted(animals.iteritems(),
key=lambda x:x[1]['cool_factor']*x[1]['popularity'])[-1][0]