[英]Pythonic way to find key of weighted minimum and maximum from a dictionary
I'm working with a dataset similar to this: 我正在使用与此类似的数据集:
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
}
}
What I'm looking to do is find the "least cool" and "coolest" animal weighted by popularity, such that: 我想要做的是找到受欢迎程度加权的“最不酷”和“最酷”的动物,这样:
> min_cool_weighted(animals)
"echidna"
> max_cool_weighted(animals)
"ostrich"
The solution that comes to me first is to create 3 arrays ( keys
, cool_factors
, and popularities
), loop through the dictionary, push all the values into the 3 arrays, then create a fourth array with each value where weighted[i] = cool_factor[i] * popularity[i]
, then take the min/max and grab the corresponding key from the key array. 首先来到我的解决方案是创建3个数组(
keys
, cool_factors
和popularities
),循环遍历字典,将所有值推入3个数组,然后创建第四个数组,每个值weighted[i] = cool_factor[i] * popularity[i]
,然后取最小值/最大值并从键阵列中获取相应的键。 However, this doesn't seem very Pythonic. 但是,这似乎不是Pythonic。
Is there a better, more expressive way? 有更好,更有表现力的方式吗?
You can use sorted
你可以使用已
sorted
Min: 闵:
sorted(animals.iteritems(),
key=lambda x:x[1]['cool_factor']*x[1]['popularity'])[0][0]
Max: 马克斯:
sorted(animals.iteritems(),
key=lambda x:x[1]['cool_factor']*x[1]['popularity'])[-1][0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.