2

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

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

{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
4

1 回答 1

1

我想你可能正在寻找defaultdict. Adefaultdict就像一个字典,除了当 KeyError 将被抛出时dict,初始化时给出的工厂函数用于创建初始值。

在您的情况下,您需要一个defaultdictfordays嵌套在一个 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
于 2011-11-09T04:06:11.193 回答