在Python中查找对象列表中的最大值

时间:2017-10-15 02:54:34

标签: python list object

我有一个对象列表。有人可以帮助返回得分最高的对象吗?例如:

objs = [
  {
    "name": "John",
    "score": 30
  },  
  {
    "name": "Josh",
    "score": 40
  },  
  {
    "name": "Jason",
    "score": 50
  },  
]

我需要一个能够返回得分最高的对象的方法。在这种情况下,它应该返回

  {
    "name": "Jason",
    "score": 50
  }

到目前为止,我试过了:

print max(objs, key=attrgetter('score'))

但它给了我AttributeError: 'dict' object has no attribute 'score'

提前致谢!

5 个答案:

答案 0 :(得分:4)

operator.attrgetter()用于属性,例如foo.bar

对于项目访问,您需要operator.itemgetter()

答案 1 :(得分:1)

熊猫

您可以将字典转换为dataframe,找到最大score的索引,提取条目并将其转换回字典。

当您拥有大量对象时,这可能会更快。

df = pd.DataFrame.from_dict(objs)
df.iloc[df['score'].idxmax(),:].to_dict()

<强>演示:

import pandas as pd

读取数据框

df = pd.DataFrame.from_dict(objs)

print(df)
    name  score
0   John     30
1   Josh     40
2  Jason     50

找到最大score

的索引
df.iloc[df['score'].idxmax(),:]

name     Jason
score       50
Name: 2, dtype: object

提取最大值并写入字典

max_obj = df.iloc[df['score'].idxmax(),:].to_dict()
print(max_obj)
{'score': 50, 'name': 'Jason'}

答案 2 :(得分:0)

max(objs,key = lambda x:x ['score'])

The key argument specifies a one-argument ordering function like that used for list.sort().

提供此功能的最紧凑方式是with lambda

>>> max(objs, key=lambda x: x['score'])
{'name': 'Jason', 'score': 50}

答案 3 :(得分:0)

不是Python专家,我保证有一种更简单,更简洁的方法可以完成。

虽然,它对我有用:

for x in objs:
    hiscore = 0
    count = 0
    if x.get('score') > hiscore:
        hiscore = x.get('score')
        count += 1
print("Highest score is {data[score]} from player {data[name]}".format(data=x))

答案 4 :(得分:0)

这也可以完成这项工作,

[a for a in objs if a["score"] == max([a["score"] for a in objs])]

返回,

[{'score': 50, 'name': 'Jason'}]

相关问题