【问题标题】:How do I return or print an attribute that's a math function between two attributes? Python如何返回或打印作为两个属性之间的数学函数的属性? Python
【发布时间】:2021-02-27 03:28:58
【问题描述】:

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

【问题讨论】:

    标签: python object constructor


    【解决方案1】:

    您只需返回多个值:

    return highest_county.name, highest_percentage
    

    在你的调用程序中:

    best_county, best_pct = highest_turnout(data)
    

    【讨论】:

    • 谢谢你。即使我之前没有介绍过您最后列出的这两个变量,我还能使用它们吗?
    • 如果您的意思是best_*,是的,您可以使用这些。这就是你引入变量的方式;你给他们一个价值。
    【解决方案2】:

    在 python 中很酷的地方是你实际上可以写以下内容:

    highest_turnout = max(data, key=lambda county: county.voters / county.population)
    

    这里,highest_turnout 是投票率最高的县。我们所做的是告诉 python 计算数据集的最大值,其中被比较的值是voters/population 即:选民的百分比。换句话说,这正是您的highest_turnout 函数在一行中所做的。您可以考虑为您的 County 类定义一个名为 get_turnout() 的方法,它只返回投票的人口百分比。

    显然highest_turnout我们可以写

    highest_turnout.name
    

    highest_turnout.voters / highest_turnout.population
    

    拥有你所追求的价值。

    【讨论】:

    • 谢谢!这很有帮助。我们还没有了解“lambda”,但它显然是找到解决方案的最简单方法。
    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 2013-07-28
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2017-06-06
    • 1970-01-01
    相关资源
    最近更新 更多