首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迭代列表集合以查找Python中的最高平均值

迭代列表集合以查找Python中的最高平均值
EN

Stack Overflow用户
提问于 2018-12-06 06:04:04
回答 1查看 221关注 0票数 0

如何创建遍历每个县的函数,计算投票率?

代码语言:javascript
复制
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]  
EN

回答 1

Stack Overflow用户

发布于 2019-08-21 11:51:58

您的类County已正确定义。但是,函数county不正确。

当在函数highest_turnout中传递数据时,您必须首先计算列表的第一个County中的投票者百分比-它位于data[0]。然后我们将“最高”设置为第一个County的国家名称,我们假设data列表中的第一个是我们所见过的最高的一个。

接下来,我们使用for循环开始迭代列表data中的所有County对象,以便传入每个County对象。

变量pct给出了在当前步骤中运行的County中投票者的百分比。if函数将其与存储在变量pct中的最高百分比进行比较。如果新的百分比高于pct (返回True),我们将更新最高百分比变量pct,从而更新县名称。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53641456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档