Django从现有lis创建一个新的运行总计列表

2024-10-05 14:26:00 发布

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

如何从另一个列表创建新的运行总计列表?假设我有以下问题:

sumbl4 = LaborDetail.objects.filter(businessunit='Birmingham').filter(endofweek__gte=datetime.date.today()-datetime.timedelta(days=60)).values_list('endofweek').annotate(hours__sum=Sum('hours')).order_by('endofweek')

sumbl3 = json.dumps(list(sumbl4), cls=DecimalJSONEncoder)

我的数据格式如下(sumbl3):

[["2017/04/23", 972.5], ["2017/04/30", 1076.5], ["2017/05/07", 1162.5], ["2017/05/14", 1055.5], ["2017/05/21", 981.0], ["2017/05/28", 945.5], ["2017/06/04", 912.0], ["2017/06/11", 1106.0], ["2017/06/18", 1059.0]]

因此,我的新列表如下所示:

[["2017/04/23", 972.5], ["2017/04/30", 2049],...

注意:我使用的是python2.7


Tags: 列表datetimedateobjectsfilterlist总计hours
3条回答

这个怎么样:

orig = [["2017/04/23", 972.5], ["2017/04/30", 1076.5], ["2017/05/07", 1162.5], ["2017/05/14", 1055.5], ["2017/05/21", 981.0], ["2017/05/28", 945.5], ["2017/06/04", 912.0], ["2017/06/11", 1106.0], ["2017/06/18", 1059.0]]

new = []
temp_sum = 0
for o in orig:
  a = o[0]
  b = o[1] + temp_sum
  new.append([a, b])
  temp_sum += b

print new

结果:

[['2017/04/23', 972.5], ['2017/04/30', 2049.0], ['2017/05/07', 4184.0], ['2017/05/14', 8261.0], ['2017/05/21', 16447.5], ['2017/05/28', 32859.5], ['2017/06/04', 65685.5], ['2017/06/11', 131565.0], ['2017/06/18', 263083.0]]

另一种获得最终列表的方法:

a = [['2017/04/23', 972.5],
 ['2017/04/30', 1076.5],
 ['2017/05/07', 1162.5],
 ['2017/05/14', 1055.5],
 ['2017/05/21', 981.0],
 ['2017/05/28', 945.5],
 ['2017/06/04', 912.0],
 ['2017/06/11', 1106.0],
 ['2017/06/18', 1059.0]]


sub = [a[0]]

for k, v in a[1:]:
    b = sub[-1][1] + v
    sub.append([k, b])

print(sub)

>>> [['2017/04/23', 972.5],
 ['2017/04/30', 2049.0],
 ['2017/05/07', 3211.5],
 ['2017/05/14', 4267.0],
 ['2017/05/21', 5248.0],
 ['2017/05/28', 6193.5],
 ['2017/06/04', 7105.5],
 ['2017/06/11', 8211.5],
 ['2017/06/18', 9270.5]]

或者以更简洁的方式,您可以创建如下示例所示的方法/函数:

def get_sum(a):
    sub = []
    for k, v in a:
        if not sub:
            sub.append([k, v])
        else:
             sub.append([k, sub[-1][1] +v])
    return sub

虽然^{}没有包含在python2.7中,但是您可以使用文档中提供的方法。你知道吗

import operator

def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    try:
        total = next(it)
    except StopIteration:
        return
    yield total
    for element in it:
        total = func(total, element)
        yield total

然后,它的用法如下所示:

data = [(1, 1), (2, 2), (3, 3)]

keys, values = zip(*data)
accumulated_data = zip(keys, accumulate(values))
# [(1, 1), (2, 3), (3, 6)]

相关问题 更多 >