关于投票率的Python指派问题:类、对象和函数

2024-09-30 01:20:08 发布

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

# implement County class here
class County:
  def __init__(self, name,population,voters):
    self.name=name
    self.population=population
    self.voters=voters

  # implement the function here

def highest_turnout(data):

highest_turnout = (data[0].voters)/(data[0].population)
for county in data:
    if (county.voters/county.population) > highest_turnout:
        highest_turnout= county
return highest_turnout

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]  

result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function
# do not remove this line!

我必须做一个python函数,在这个函数中返回最高的投票率我只是一个编程初学者,类资源并没有真正的帮助。任何帮助都将不胜感激。谢谢。在

方向:
●首先,使用对象的人口和选民属性,找出投票率最高的县,即投票人口的最高百分比
●然后,返回一个元组,其中包含投票率最高的县的名称和 按顺序投票的人口百分比;百分比应为 表示为0到1之间的数字

我已经写好了课。在

TypeError: '>' not supported between instances of 'float' and 'County'

我得到了这个错误。我认为我的类是正确的,但我不太确定如何处理这个函数。指示还说要以元组的形式返回县名和最高投票率,但我不太确定如何返回。请帮忙。非常感谢。在


Tags: thenameselfdatapopulationcountylancasterhighest
2条回答

你的问题是:

highest_turnout = (data[0].voters)/(data[0].population)
for county in data:
    if (county.voters/county.population) > highest_turnout:
        highest_turnout= county

所以,让我们考虑一下这个循环的第一个迭代(好吧,第二个——关于data[1]的那个,因为data[0]迭代在这里不相关)。highest_turnout只是定义为选民/人口的float。你把它和另一个国家的选民/人口相比较。有道理。在

现在让我们考虑一下voters / populationdata[0]高。因此,if条件被触发。highest_turnout被设置为data[1],这是county的当前值。在

我们继续下一个迭代,对于data[2],您将得到错误:

^{pr2}$

在第一次迭代中,highest_turnout是一个float,您在两个floats之间使用了运算符>。但是现在highest_turnout是一个County,而不是float-当你在if语句中给它分配一个新值时,你就改变了它的类型。由于County不是一种数字类型,python不知道如何将其与float进行比较。所以你在这里看到的错误。在

解决方案是使highest_turnout成为被比较的值,而不是这些值来自的国家:

highest_turnout = county.voters / county.population

另一种解决办法是将一个国家一直保留下来:

highest_turnout = data[0]
for county in data:
    if (county.voters/county.population) > (highest_turnout.voters/highest_turnout.population):
        highest_turnout = county

你只需要确保你没有在没有意识到的情况下改变任何变量的类型。在

或者,使用max函数,而不是使用循环来查找最大道岔县:

class County:

    def __init__(self, name, population, voters):
        self.name = name
        self.population = population
        self.voters = voters

    def get_turnout(self):
        # return the turnout as a number between 0 - 1.
        return self.voters / self.population

def highest_turnout(counties):
    max_county = max(counties, key=lambda c: c.get_turnout())
    return (max_county.name, max_county.get_turnout())

相关问题 更多 >

    热门问题