python字典列表仅更新1个属性并跳过其他属性

2024-05-03 14:31:15 发布

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

我有一个包含公司对象的列表:

companies_list = [companies1, companies2]

我有以下功能:

def get_fund_amount_by_year(companies_list):
    companies_length = len(companies_list)
    for idx, companies in enumerate(companies_list):
        companies1 = companies.values_list('id', flat=True)
        funding_rounds = FundingRound.objects.filter(company_id__in=companies1).order_by('announced_on')

        amount_per_year_list = []
        for fr in funding_rounds:
            fr_year = fr.announced_on.year
            fr_amount = fr.raised_amount_usd
            if not any(d['year'] == fr_year for d in amount_per_year_list):
                year_amount = {}
                year_amount['year'] = fr_year
                for companies_idx in range(companies_length):
                    year_amount['amount'+str(companies_idx)] = 0
                    if  companies_idx == idx:
                        year_amount['amount'+str(companies_idx)] = fr_amount
                amount_per_year_list.append(year_amount)
            else:
                for year_amount in amount_per_year_list:
                    if year_amount['year'] == fr_year:
                        year_amount['amount'+str(idx)] += fr_amount

    return amount_per_year_list

问题是生成的字典列表只更新了一个amount属性。你知道吗

如您所见,“amount0”包含所有“0”金额:

[{'amount1': 12100000L, 'amount0': 0, 'year': 1999}, {'amount1': 8900000L, 'amount0': 0, 'year': 2000}]

我做错什么了?你知道吗


Tags: in列表forbyifframountyear
1条回答
网友
1楼 · 发布于 2024-05-03 14:31:15

我把正在构建的字典列表放在循环中,所以当它迭代时,它重写了最后的输入。我把它改成:

def get_fund_amount_by_year(companies_list):
    companies_length = len(companies_list)
    **amount_per_year_list = []**
    for idx, companies in enumerate(companies_list):
        companies1 = companies.values_list('id', flat=True)
        funding_rounds = FundingRound.objects.filter(company_id__in=companies1).order_by('announced_on')

相关问题 更多 >