我有2个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)
如果您有建议如何提高此代码的效率,欢迎您在评论或答案中发布您的建议。
答案 0 :(得分:0)
我假设您提供的示例存在拼写错误,因为:
hah
是list
dict
,每个字典中只有一个key
。相反,它应该是单一字典。 ISN&#39;吨?此外,对于键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]}