如何通过在Python中调用函数在对象列表中查找最大值

时间:2018-12-19 11:52:30

标签: python class max

我想在python中定义一个函数,该函数返回对象列表中计算出的变量的最大值。我首先创建了一个类并定义了新变量,以计算以千为单位的人均平均GDP(self.percapita = 1000 * self.gdp / self.population):

class Country():    
  def __init__(self, name, population, gdp) :
    self.name = name
    self.population = population
    self.gdp = gdp
    self.percapita = 1000 * self.gdp / self.population

我输入实例列表:

unitedstates = Country("unitedstates", 326766748, 19390600)
china = Country("china", 1415045928 , 12014610)
japan = Country("japan", 127185332, 4872135)

list = [unitedstates, china, japan]

我需要您的帮助来创建一个函数,该函数返回人均收入最高的国家和一个包含该国家的名称和人均值的元组:

 def highest_percapita(list) :

我知道以下代码会生成所需的输出,但是我需要创建上述函数:

 from operator import attrgetter
 highest_percapita = max(list, key=attrgetter('percapita'))
 print(highest_percapita.name)
 print(highest_percapita.name, highest_percapita.percapita)

谢谢!

1 个答案:

答案 0 :(得分:2)

这应该做到:

from operator import attrgetter


class Country():
    def __init__(self, name, population, gdp):
        self.name = name
        self.population = population
        self.gdp = gdp
        self.percapita = 1000 * self.gdp / self.population


def highest_percapita(list) :
    return max(list, key=attrgetter('percapita'))

unitedstates = Country("unitedstates", 326766748, 19390600)
china = Country("china", 1415045928 , 12014610)
japan = Country("japan", 127185332, 4872135)

lst = [unitedstates, china, japan]

print(highest_percapita(lst).name)

输出

unitedstates