簡體   English   中英

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

[英]Find maximum in list of objects in Python

我有一個對象列表。 有人可以幫忙退還得分最高的物體嗎? 例如:

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'

提前致謝!

operator.attrgetter()用於屬性,例如foo.bar

對於項目訪問,您需要operator.itemgetter()代替。

大熊貓

您可以將字典轉換為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'}

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

key參數指定一個單參數排序函數,例如用於list.sort()的函數。

提供功能最緊湊的方法是使用lambda

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

不是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))

這也應該做的

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

退貨

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM