Jason
Jason

Reputation: 1

How to find the max value in a list of objects by calling a function in Python

I would like to define a function in python that returns the max value of a calculated variable in a list of objects. I have first created a class and defined the new variable to calculate the average GDP per capita in thousands (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

I enter the list of instances:

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

list = [unitedstates, china, japan]

I need your help to create a function that returns the country with the highest percapita and a tuple that contains the country's name and the percapita value:

 def highest_percapita(list) :

I know that the following code generates the desired outputs, but I need to create the above function instead:

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

Thanks!

Upvotes: 0

Views: 437

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

This should do it:

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)

Output

unitedstates

Upvotes: 2

Related Questions