python - 如何返回或打印作为两个属性之间的数学函数的属性?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!
解决方案
您只需返回多个值:
return highest_county.name, highest_percentage
在您的调用程序中:
best_county, best_pct = highest_turnout(data)
推荐阅读
- compiler-errors - 埃菲尔:or and and and 中的本地声明编译失败
- javascript - 如何在 JavaScript 中使用析构函数——在将传递给 React 组件的辅助函数中?
- spring-boot - 使用 logback-spring.xml 时如何从属性文件中注入 Logback loglevel
- php-7.2 - PHPSpreadsheet and PHP7.2
- postgresql - postgresql -- 通过从多个表中插入数据来创建物化视图
- mysql - 如何使用 IN() 函数搜索精确值
- typescript - 文件夹内的特定 tsconfig.json 规则
- socket.io - socket.io 从一个命名空间向另一个命名空间发出消息
- javascript - 如何获取数组内的对象以显示在文档或控制台上
- javascript - 将字节数组从后面的代码发送到 ajax 调用