python - 迭代一组列表以找到 Python 中的最高平均值
问题描述
如何创建迭代每个县的函数,计算选民投票率?
class County:
def __init__(self, init_name, init_population, init_voters) :
self.name = init_name
self.population = init_population
self.voters = init_voters
def highest_turnout(data) :
100 * (self.voters / self.population)
allegheny = County("allegheny", 1000490, 645469)
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]
解决方案
您的课程County
定义正确。但是,功能county
不正确。
在函数中传递数据时highest_turnout
,您必须首先计算County
列表第一个中选民的百分比 - 它位于data[0]
. 然后我们将“highest”设置为第一个的国家名称County
,我们假设data
列表中的第一个是我们见过的最高的。
接下来,我们使用for
循环开始迭代County
列表data
中的所有对象,以便传入每个County
对象。
该变量为我们提供了当前步骤中正在运行pct
的投票者的百分比。County
该if
函数将其与存储在变量中的最高百分比进行比较pct
。如果新百分比高于pct
(返回 True),我们更新最高百分比变量pct
,从而更新县名。
def highest_turnout(data) :
highest_pct = data[0].voters / data[0].population
highest = data[0].name
for county in data :
pct = county.voters / county.population
if pct > highest_pct :
highest_pct = pct
highest = county.name
推荐阅读
- laravel - Laravel 发送预定的电子邮件,其中包含最近 24 小时收到的错误计数的消息行
- xquery - Xquery 中的 XSLT 风格的小型转换?
- java - 在 Spring Boot 应用程序中使用 AspectJ Load Time Weaving 时构建结果不一致
- javascript - 如何使用 javascript 提取模式并将其嵌入到 span 元素中?
- elasticsearch - 心跳 icmp 配置主机别名
- c - 通过赋值在 C 中设置环境变量
- macos - 如何将 AppleScript 脚本返回列表中的值分配给 Automator 中的变量?
- dialogflow-es - 从实现中的回退意图获取输出上下文
- java - 如何将 {0,0} 放入数组并在遇到 if 语句时更改它
- sql - 使用 sql distinct 或 groupby 时忽略字符