[Answer]-Fetchall for loop multiple list to one

1๐Ÿ‘

โœ…

If you simply want to transpose a set of lists in this format:

data = [[x, y], [x, y], [x, y]]

into this format:

[[x, x, x], [y, y, y]]

you can use the built-in zip function:

results = zip(data)

Thus, your code would become:

def WeekCombo(request):
    fweeks = []
    cursor = connections['nocdb'].cursor()
    for start, end in WeeklyReports().FourWeeks(2013, 48):
        cursor.execute("""
            SELECT DISTINCT (p.name) AS platform,
                COUNT(e.id ) AS count
            FROM event e, lu_platform p
            WHERE e.platform_id = p.id
            AND e.sourcetype_id = 1
            AND e.event_datetime BETWEEN %s AND %s
            AND e.sender_id  NOT IN ( 759, 73 )
            GROUP BY p.name
            ORDER BY p.name""", [start, end] )
        fweeks.extend(cursor.fetchall())
    fweeks = zip(fweeks)
    return render_to_response('form.html', {'fweeks': fweeks}, 
                              context_instance=RequestContext(request))

Leave a comment