Python 从API获取数据,每年求和2个值
我想从API获取数据,其结构如下所示: 地区-通过-性别-年份-价值 这个api显示了有多少来自这个国家的人通过了考试,但同一年有两行,但性别不同(男性和女性)。 我想计算每年的总价值,例如: CountryA通过男2019 12 CountryA于2019年30岁通过女性考试 所以结果应该是42。 不幸的是,我的方法只返回女性的值 我试着这样做:Python 从API获取数据,每年求和2个值,python,api,Python,Api,我想从API获取数据,其结构如下所示: 地区-通过-性别-年份-价值 这个api显示了有多少来自这个国家的人通过了考试,但同一年有两行,但性别不同(男性和女性)。 我想计算每年的总价值,例如: CountryA通过男2019 12 CountryA于2019年30岁通过女性考试 所以结果应该是42。 不幸的是,我的方法只返回女性的值 我试着这样做: def task2(self,data,district=None): passed = {stat.year: stat.amount f
def task2(self,data,district=None):
passed = {stat.year: stat.amount for stat in data
if self.getPercentageAmountOfPassed(stat.status,stat.district,stat.year)}
def getPercentageAmountOfPassed(self,status,district,year):
return status == 'passed' and district == 'CountryA' and year <= 2019
def task2(自身、数据、地区=无):
已通过={stat.year:数据中stat的stat.amount
如果self.getPercentageAmountOffPassed(stat.status、stat.district、stat.year)}
def GetPercentageAmountOffPassed(自我、状态、地区、年份):
返回状态=='passed'和地区=='CountryA'和年份发生这种情况是因为您在同一年覆盖了以前的条目。您需要将它们相加:
from collections import defaultdict
def sum_per_year(data):
passed = defaultdict(int)
for stat in data:
if getPercentageAmountOfPassed(stat.status, stat.district, stat.year):
passed[int(stat.year)] += stat.amount
return passed
你能显示数据的样本值吗?@DeveshKumarSingh补充说该数据没有数字可加,例如12和30@DeveshKumarSingh重新编辑