循环遍历不同长度的查询

时间:2017-05-23 20:15:59

标签: python django python-3.x

我使用zip同时循环遍历两个查询的结果。但是在某些情况下,结果的长度不一样。在这些情况下,我想将首先结束的查询的值设置为0.始终,occupancy_agency始终结束,因为它是第一个查询的子集。具体来说,它是occupancy_agency_y['supply']occupancy_agency_y['available']。我试图提出一个解决方案,但无法弄清楚如何将其与zip结合使用,这样我就可以同时遍历这两个结果。

def occupancy_data(area_id, description, period, agency_id):  
    occupancy = Occupancy.objects.filter(description=description) \
        .values('start_date') \
        .annotate(supply_total=Sum('supply')) \
        .annotate(available_total=Sum('available')) \
        .order_by('start_date')

    occupancy_agency = Occupancy.objects.filter(description=description, agency_id=agency_id) \
        .values('start_date',) \
        .annotate(supply=Sum('supply')) \
        .annotate(available=Sum('available')) \
        .order_by('start_date')


    x = []
    _input = occupancy.values('start_date')
    for row in _input:
        x.append("Uge " + str(int(row['start_date'].strftime("%V"))))

    y = []
    for occupancy_y, occupancy_agency_y in zip(occupancy, occupancy_agency):
        comp_supply = (occupancy_y['supply_total'] - occupancy_agency_y['supply'])
        comp_available = (occupancy_y['available_total'] - occupancy_agency_y['available'])

        occupancy_combined = ((comp_supply - comp_available) / comp_supply)

        y.append(occupancy_combined)
    return {'x': x, 'y': y}

1 个答案:

答案 0 :(得分:2)

itertools提供了zip_longest函数,可以完成此操作......

for occupancy_y, occupancy_agency_y in zip_longest(occupancy, occupancy_agency, fillvalue=0):
    ...

或者,或许:

for occupancy_y, occupancy_agency_y in zip_longest(occupancy, occupancy_agency, fillvalue={}):
    comp_supply = (occupancy_y['supply_total'] - occupancy_agency_y.get('supply', 0))
    comp_available = (occupancy_y['available_total'] - occupancy_agency_y.get('available', 0))

    occupancy_combined = ((comp_supply - comp_available) / comp_supply)

    y.append(occupancy_combined)