首页 > 解决方案 > 如何返回或打印作为两个属性之间的数学函数的属性?Python

问题描述

我对 Python 非常陌生,并且已经检查了有关此主题的其他三篇文章,但未能成功实现它们。

从本质上讲,我试图返回投票率最高的县的名称和百分比。我似乎无法弄清楚如何返回或打印后一部分,因为我没有数学部分(选民/人口)的属性。

我玩过一些类似的东西:

def percentage(self, turnout):
  self.turnout = voters / population

抱歉,如果这篇文章格式不正确 - 这是全新的!提前致谢。

class County: 
  def __init__(self, name, population, voters):
    self.name = name
    self.population = population
    self.voters = voters

def highest_turnout(data):

  highest_county = data[0]
  highest_percentage = (data[0].voters / data[0].population)

  for county in data:
    if (county.voters / county.population) > highest_percentage:
      highest_county = county
      highest_percentage = (county.voters / county.population)
  return highest_county.name

  
  # implement the function here


# your program will be evaluated using these objects 
# it is okay to change/remove these lines but your program
# will be evaluated using these as inputs
allegheny = County("allegheny", 1000490, 645469) # this is an object
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]  

result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function
# do not remove this line!

标签: pythonobjectconstructor

解决方案


您只需返回多个值:

return highest_county.name, highest_percentage

在您的调用程序中:

best_county, best_pct = highest_turnout(data)

推荐阅读