从字典中求加权最小值和最大值的Pythonic方法

2024-04-25 04:46:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的数据集类似于:

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个数组(keyscool_factorspopularities),循环遍历字典,将所有值推入3个数组,然后创建第四个数组,每个值在weighted[i] = cool_factor[i] * popularity[i]处,然后取min/max并从键数组中获取相应的键。然而,这似乎不是很Python。你知道吗

有没有更好、更具表现力的方式?你知道吗


Tags: 数据数组minmaxanimalsfactorechidnacool
2条回答

maxmin应该足够了

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]

相关问题 更多 >