我正在处理一个与此类似的数据集:
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_factors和popularities),遍历字典,将所有值推入3个数组中,然后创建第四个数组,其中包含weighted[i] = cool_factor[i] * popularity[i]的每个值,然后取min/max并从键数组中获取相应的键。然而,这看上去不太像毕达通。
有没有更好、更有表现力的方法?
发布于 2013-11-08 01:15:21
max和min应该足够了
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'发布于 2013-11-08 01:15:50
您可以使用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]https://stackoverflow.com/questions/19849853
复制相似问题