我有两个dicts列表:
hah = [{1:[datetime(2014, 6, 26, 13, 7, 27), datetime(2014, 7, 26, 13, 7,27)]},
{2:datetime(2014, 5, 26,13,7,27)}]
dateofstart = [{1:datetime(2013, 6, 26, 13, 7, 27)}, {2:datetime(2013, 6,
26,13,7,27)}]` (just examples).
我需要创建一个新的dicts列表,该列表包含相同的键,并且作为一个值,hah和dateofstart的日期之间存在差异。
它应该是这样的:
[{1:[365, 334]}, {2:[390]}]
当我试着自己做的时候,我得到了这个代码
dif = list()
diff = list()
for start in dateofstart:
for time in hah:
if start.keys() == time.keys():
starttime = start.values()
timeofpay = time.values()
for payments in timeofpay:
dif.append(starttime.pop(0) - payments)
diff.append({str(start.keys()):str(dif)})
它运行时出现以下错误:
Traceback (most recent call last):
File "/Users/mihailbasmanov/Documents/date.py", line 78, in <module>
dif.append(starttime.pop(0) - payments)
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'list'
版本:
(几乎(是我一个人做的。以下是结果代码:
for start in dateofstartbuyer:
for time in hah:
if start.keys() == time.keys():
starttime = start.values()
starttimetime = starttime.pop(0)
timeofpay = time.values()
for payments in timeofpay:
if type(payments) == list:
for wtf in payments:
dif.append(wtf - starttimetime)
else:
dif.append(payments - starttimetime)
key = str(start.keys())
diff.append({key[1:2]:str(dif)})
dif = list()
print(diff)
如果你有关于如何提高代码效率的建议,欢迎在评论或答案中发表你的建议。
我假设您提供的示例存在拼写错误问题,因为:
-
hah
是dict
的list
,每个字典中只有一个key
。相反,它应该是一本字典。不是吗?此外,对于关键字2
,值是单个datetime()
对象,而不是list
。它不是假定为[datetime]
吗?hah = [{1:[datetime(2014, 6, 26, 13, 7, 27), datetime(2014, 7, 26, 13, 7,27)]}, {2:datetime(2014, 5, 26,13,7,27)}]
因此,我假设hah
和dateofstart
为dict
对象。下面是代码。如果我的任何假设都不正确,请告诉我。
>>> hah = {1:[datetime(2014, 6, 26, 13, 7, 27), datetime(2014, 7, 26, 13, 7,27)],
... 2:[datetime(2014, 5, 26,13,7,27)]}
>>> dateofstart = {1:datetime(2013, 6, 26, 13, 7, 27), 2:datetime(2013, 6,26,13,7,27)}
>>> dicts = {}
>>> for key, values in hah.items():
... dicts[key] = [(value - dateofstart[key]).days for value in values]
...
>>> dicts
{1: [365, 395], 2: [334]}