我正在尝试创建一个涉及timedeltas的字典字典,该字典应该转换为天数(四舍五入到1 d.p.)。
输入是OrderedDict
和values_list。初始化的OrderedDict
和values_list如下所示:
OrderedDict(
[('Jul 2015', defaultdict(<function __main__.<lambda>>, {})),
('Aug 2015', defaultdict(<function __main__.<lambda>>, {})),
('Sep 2015', defaultdict(<function __main__.<lambda>>, {})),
('Oct 2015', defaultdict(<function __main__.<lambda>>, {})),
('Nov 2015', defaultdict(<function __main__.<lambda>>, {})),
('Dec 2015', defaultdict(<function __main__.<lambda>>, {}))]
)
values_list = [
(
datetime.date(2015, 7, 1),
datetime.timedelta(1, 11111),
datetime.timedelta(2, 22222),
datetime.timedelta(3, 33333)
),
(
datetime.date(2015, 8, 1),
datetime.timedelta(4, 44444),
datetime.timedelta(5, 55555),
None
),
...
]
,输出应如下所示:
output_matrix = {
'Jul 2015': {
'time_1': 0.1,
'time_2': 0.3,
'time_3': 0.4
}
'Aug 2015': {
'time_1': 0.5,
'time_2': 0.6,
'time_3': 0
}
...
}
请注意,None
timedeltas会转换为0
。
这看起来很容易,但到目前为止我得到的解决方案真的很难看,而且我确信有更好的方法。
我丑陋的解决方案:
matrix = OrderedDict()
today = timezone.now()
tzinfo = timezone.get_current_timezone()
headers = ['Time 1', 'Time 2', 'Time 3'] # Used elsewhere, could possibly use here?
# Initialise OrderedDict
for i in range(5, -1, -1):
d = datetime(today.year, today.month, 1, tzinfo=tzinfo) - relativedelta(months=i)
matrix[d.strftime("%b %Y")] = defaultdict(lambda: 0)
matrix = build_matrix(matrix, values_list)
def build_matrix(matrix, values_list)
''' Populates a matrix and converts timedeltas into days. '''
for month, time1, time2, time3 in values_list:
month_label = month.strftime("%b %Y")
if time1 is not None:
matrix[month_label]['Time 1'] = round(time1.seconds/60/60/24, 1)
if time2 is not None:
matrix[month_label]['Time 2'] = round(time2.seconds/60/60/24, 1)
if time3 is not None:
matrix[month_label]['Time 3'] = round(time3.seconds/60/60/24, 1)
return matrix
如何改进此解决方案?