首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python投票率分配-类和对象

Python投票率分配-类和对象
EN

Stack Overflow用户
提问于 2019-03-04 12:43:55
回答 1查看 561关注 0票数 0

我需要写一个代码来显示这个县的名称:(i)投票率最高,(ii)投票的人口百分比。你能帮我吗,因为我太困惑了。以下是我所做的工作:

代码语言:javascript
复制
class County: 
   def __init__(self, init_name, init_population, init_voters) :
   self.population = init_population
   self.voters = init_voters

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]  

def highest_turnout(self):
   highest = self[0]
   highest_voters = self[0].voters
   for county in data:
      if county.voters > highest_voters:
         highest = county

result = highest_turnout(self)
print(result)
EN

回答 1

Stack Overflow用户

发布于 2019-03-05 03:11:11

从注释中总结建议,highest_turnout函数需要return highest,否则在函数结束后highest值将丢失。然后,不是将self传递给highest_turnout,而是在data中传递

代码语言:javascript
复制
class County:
    def __init__(self, init_name, init_population, init_voters):
        self.name = init_name
        self.population = init_population
        self.voters = init_voters

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]  

def highest_voter_turnout(data):
    '''iterate over county objects comparing county.voters values; 
    returns county object with max voters attribute'''
    highest_voters = data[0]
    for county in data:
        if county.voters > highest_voters.voters:
            highest_voters = county
    return highest_voters

result_highest_voter_turnout = highest_voter_turnout(data)

print(result_highest_voter_turnout.name)

到目前为止,这将返回并显示“(i)投票率最高的县”(即allegheny)的名称。

现在可以创建一个类似的函数来计算具有最高"(ii)人口投票百分比“的县(也是评论中提到的一种方法)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54976762

复制
相关文章

相似问题

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