Python投票者投票率分配类与obj

2024-09-30 01:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要写一个代码来显示该县的名称:(I)投票率最高的县和(ii)投票的人口百分比。你能帮我一下吗?因为我很困惑。以下是我所做的:

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)

Tags: selfinitdefpopulationcountylancasterhighestphiladelphia
1条回答
网友
1楼 · 发布于 2024-09-30 01:34:13

总结来自注释的建议,highest_turnout函数需要return函数highest,否则在函数完成highest值后,该函数将丢失。 然后不是传入selfhighest_turnout,而是传入data

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)

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

现在可以创建一个类似的函数来计算投票率最高的县(ii)(在评论中也提到了一种方法)。在

相关问题 更多 >

    热门问题