fetchall for循环多个列表到一个

时间:2013-12-18 21:00:43

标签: python django

我的django中有以下内容:

我的models.py

import datetime
from datetime import datetime, date, timedelta
import dateutil
from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, WEEKLY, MO, SU
from django.utils import timezone
from django.db import models
from django.db import connections

class WeeklyReports(models.Model):
    def FourWeeks(self, year, week):
        self.year = year
        self.week = week
        end = datetime(year, 1, 1) + relativedelta(weeks=week-1, weekday=SU)
        start = end - relativedelta(weeks=4, weekday=MO)
        mint, maxt = datetime.min.time(), datetime.max.time()
        for dt in rrule(WEEKLY, start, count=4):
            yield dt.combine(dt, mint), dt.combine(dt + timedelta(days=6), maxt)

views.py:

import itertools
from itertools import chain, groupby
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from datetime import datetime 
from weeklyreport.models import WeeklyReports
from django.http import HttpResponse
from django.db import connections

def WeekCombo(request):
    fweeks = []
    cursor = connections['nocdb'].cursor()
    year = 2013
    week = 48
    w = WeeklyReports()
    for start, end in w.FourWeeks(year, week):
        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] )
        r = [i for i in chain.from_iterable(cursor.fetchall())]
        fweeks.append([n for n in r])
    return render_to_response('form.html', {'fweeks': fweeks}, 
                              context_instance=RequestContext(request))

使用我的fetchall循环,我得到四个列表:

[u'Cust01', 191L, u'Cust02', 21L, u'Cust03', 420L]
[u'Cust01', 17L, u'Cust02', 96L, u'cust03', 11L]
[u'Cust01', 44L, u'Cust02', 225L, u'Cust03', 356L]
[u'Cust01', 76L, u'Cust02', 304L, u'Cust03', 157L, u'Cust04', 212L]

我是从这四个单独的查询列表中创建一个嵌套列表的方法吗?我如何在循环中合并这个列表?

[['Cusr01','Cust02','Cust03', 'Cust04'], [191, 21, 420], [17, 96, 11], [44, 225, 356],
[76, 304, 157, 121]]

1 个答案:

答案 0 :(得分:1)

如果您只是想以这种格式转置一组列表:

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

采用以下格式:

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

您可以使用内置的zip功能:

results = zip(data)

因此,您的代码将成为:

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))