说我有一个列表:
t = [[datetime.datetime(2015, 6, 20, 0, 0), 0],
[datetime.datetime(2015, 6, 20, 0, 0), 43],
[datetime.datetime(2015, 6, 20, 0, 0), 24],
[datetime.datetime(2015, 6, 20, 0, 0), 145],
[datetime.datetime(2015, 6, 20, 0, 0), 249],
[datetime.datetime(2015, 6, 20, 0, 0), 347],
[datetime.datetime(2015, 6, 21, 0, 0), 191],
[datetime.datetime(2015, 6, 21, 0, 0), 46],
[datetime.datetime(2015, 6, 21, 0, 0), 19],
[datetime.datetime(2015, 6, 21, 0, 0), 88],
[datetime.datetime(2015, 6, 21, 0, 0), 181],
[datetime.datetime(2015, 6, 21, 0, 0), 250]]
我希望通过列表中的第一项将这些组合在一起 - 这样我就可以了(无论是列表还是字典形式都可以,我可以将一个转换为另一个):
t = [datetime.datetime(2015, 6, 20, 0, 0), 750],
[datetime.datetime(2015, 6, 21, 0, 0), 576]]
我尝试将newdict = dict(t)
分组,但是newdict只返回列表中的最后一个值,这不是我想要的。
newdict = {datetime.datetime(2015, 6, 20, 0, 0): 347,
datetime.datetime(2015, 6, 21, 0, 0): 250}
我想整理相同datetime.datetime值的值。
欢迎任何建议 - 谢谢!
答案 0 :(得分:1)
您可以使用itertools.groupby
,您可以使用第一个元素对列表进行分组,然后遍历分组列表以对第二个元素求和。
示例 -
>>> from itertools import groupby
>>> import datetime
>>>
>>> t = [[datetime.datetime(2015, 6, 20, 0, 0), 0],
... [datetime.datetime(2015, 6, 20, 0, 0), 43],
... [datetime.datetime(2015, 6, 20, 0, 0), 24],
... [datetime.datetime(2015, 6, 20, 0, 0), 145],
... [datetime.datetime(2015, 6, 20, 0, 0), 249],
... [datetime.datetime(2015, 6, 20, 0, 0), 347],
... [datetime.datetime(2015, 6, 21, 0, 0), 191],
... [datetime.datetime(2015, 6, 21, 0, 0), 46],
... [datetime.datetime(2015, 6, 21, 0, 0), 19],
... [datetime.datetime(2015, 6, 21, 0, 0), 88],
... [datetime.datetime(2015, 6, 21, 0, 0), 181],
... [datetime.datetime(2015, 6, 21, 0, 0), 250]]
>>> x = groupby(t, lambda x1: x1[0])
>>> newt = []
>>> for y, z in x:
... l1 = []
... for a in z:
... l1.append(a[1])
... newt.append([y,sum(l1)])
...
>>> newt
[[datetime.datetime(2015, 6, 20, 0, 0), 808], [datetime.datetime(2015, 6, 21, 0, 0), 775]]
答案 1 :(得分:0)
包含groupby()
的一行代码:
list((k, sum(x[1] for x in g)) for k, g in groupby(sorted(t), lambda x: x[0]))
使用dict
来计算:
count_dict = {}
for key, value in t:
count_dict[key] = count_dict.get(key, 0) + value
或defaultdict
:
from collections import defaultdict
count_dict = defaultdict(int)
for key, value in t:
count_dict[key] += value
答案 2 :(得分:-1)
d = {}
for el in t:
if el[0] not in d:
d[el[0]] = el[1]
else:
d[el[0]] += el[1]
print(d)