如何返回或打印';两个属性之间的数学函数是什么?python

如何返回或打印';两个属性之间的数学函数是什么?python,python,object,constructor,Python,Object,Constructor,我对Python非常陌生,并且已经检查了关于这个主题的其他三篇文章,但是没有能够成功地实现它们 基本上,我试图返回投票率和投票率最高的县的名称。我似乎不知道如何返回或打印后面的部分,因为我没有数学部分(选民/人口)的属性 我玩过一些东西,比如: def percentage(self, turnout): self.turnout = voters / population 抱歉,如果这篇文章格式不正确-这都是非常新的!提前谢谢 class County: def __init__(

我对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!

您只需返回多个值:

return highest_county.name, highest_percentage
在您的呼叫程序中:

best_county, best_pct = highest_turnout(data)

python中非常酷的一点是,实际上您可以编写以下内容:

highest_turnout = max(data, key=lambda county: county.voters / county.population)
在这里,
投票率最高的县是投票率最高的县。我们所做的是让python计算数据集的最大值,其中比较的值是
选民/人口
即:来投票的选民百分比。换句话说,这正是
最高投票率
函数在一行中所做的。您可以考虑为您的<代码>县<代码>类定义一种方法,称为<代码> GETO-TUROUTE()/CUT>,它只返回所投票的人口百分比。 显然,通过
最高投票率
我们可以写

highest_turnout.name


拥有你所追求的价值。

谢谢!这很有帮助。我们还没有了解“lambda”,但这显然是找到解决方案的最简单方法。谢谢你。即使我以前没有介绍过这两个变量,我仍然可以使用你最后列出的这两个变量吗?如果你是说
best.*
,是的,你可以使用它们。这就是你如何引入变量;你给他们一个价值。
highest_turnout.voters / highest_turnout.population