我需要写一个代码来显示这个县的名称:(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)发布于 2019-03-05 03:11:11
从注释中总结建议,highest_turnout函数需要return highest,否则在函数结束后highest值将丢失。然后,不是将self传递给highest_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)到目前为止,这将返回并显示“(i)投票率最高的县”(即allegheny)的名称。
现在可以创建一个类似的函数来计算具有最高"(ii)人口投票百分比“的县(也是评论中提到的一种方法)。
https://stackoverflow.com/questions/54976762
复制相似问题