希望我能解释我想要完成的事情。我对实现我的结果没有任何问题,但我知道这可能不是最好的方法。
我有一个表格,其中包含一些按日期排列的条目。我试图从当月获取这些条目,并按周将它们排列成一个列表,然后从表中为一周中的每一天求和一个值。最终结果看起来像这样:
{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
请您参考如下方法:
我认为您可能正在寻找 defaultdict . defaultdict 就像一本字典,除了当使用 dict 抛出 KeyError 时,初始化时给出的工厂函数用于创建初始值。
在您的情况下,您需要一个defaultdict days 嵌套在一个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
