簡體   English   中英

如何返回或打印兩個屬性之間的數學 function 屬性? Python

[英]How do I return or print an attribute that's a math function between two attributes? Python

我對 Python 非常陌生,並且已經檢查了有關此主題的其他三個帖子,但未能成功實施。

從本質上講,我試圖返回投票率最高的縣的名稱和百分比。 我似乎無法弄清楚如何返回或打印后一部分,因為我沒有數學部分(選民/人口)的屬性。

我玩過一些類似的東西:

def percentage(self, turnout):
  self.turnout = voters / population

抱歉,如果這篇文章格式不正確 - 這是全新的。 提前致謝。

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

def highest_turnout(data):

  highest_county = data[0]
  highest_percentage = (data[0].voters / data[0].population)

  for county in data:
    if (county.voters / county.population) > highest_percentage:
      highest_county = county
      highest_percentage = (county.voters / county.population)
  return highest_county.name

  
  # implement the function here


# your program will be evaluated using these objects 
# it is okay to change/remove these lines but your program
# will be evaluated using these as inputs
allegheny = County("allegheny", 1000490, 645469) # this is an object
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!

您只需返回多個值:

return highest_county.name, highest_percentage

在您的調用程序中:

best_county, best_pct = highest_turnout(data)

python 中非常酷的是你實際上可以寫以下內容:

highest_turnout = max(data, key=lambda county: county.voters / county.population)

在這里, highest_turnout是投票率最高的縣。 我們所做的是告訴 python 計算數據集的最大值,其中比較的值是voters/population ,即:選民的百分比。 換句話說,這正是你的最高投票highest_turnout在一行中所做的。 您可以考慮為您的County class 定義一個名為get_turnout()的方法,它只返回投票的人口百分比。

顯然,我們可以用highest_turnout的投票率寫

highest_turnout.name

highest_turnout.voters / highest_turnout.population

擁有你所尋求的價值觀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM