希望我能解释我要完成的工作。我没有问题,但我知道这可能不是最好的方法。

我有一张表,其中按日期列出了一些条目。我正在尝试从当月获取这些条目,并将它们按周排列到一个列表中,然后对一周中的每一天从表中求和。最终结果将如下所示:

{44: {4: Decimal('2.80'), 5: Decimal('6.30')}, 45: {1: Decimal('8.90'), 2: Decimal('10.60')}}


我有解决办法。但是,我知道这不是最好的方法。关于如何使它更好的任何想法?

#Queries the database and returns time objects that have fields 'hours' and 'date'
time = self.month_time()

r = {}
for t in time:
    #Get the week of the year number
    week = t.date.isocalendar()[1]

    #Get the day of the week number
    day = t.date.isoweekday()

    if week not in r:
        r.update({week:{}})
    if day not in r[week]:
        r[week][day] = 0

    r[week][day] = r[week][day] + t.hours

最佳答案

我认为您可能正在寻找defaultdictdefaultdict就像字典一样,除了使用dict抛出KeyError时,初始化时给出的工厂函数用于创建初始值。

对于您的情况,您需要在defaultdict中嵌套一个days for weeks。我认为这将为您工作:

from collections import defaultdict

r = defaultdict(lambda: defaultdict(int))
for t in time:
    week = t.date.isocalendar()[1]
    day = t.date.isoweekday()
    r[week][day] += t.hours

关于python - Python/Django-按日和周汇总的构建列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8060031/

10-12 17:00