我在Python 3.7中有2个列表:一个用于标签,另一个用于值。 每个标签包含一个各自的值,并且有重复的标签。
如何将这些重复项从标签列表中删除,并汇总它们各自的值?
labels = ['05/Feb/2019', '05/Feb/2019', '05/Feb/2019', '01/Feb/2019']
values = ['2', '5', '7', '4']
labels = ['05/Feb/2019', '01/Feb/2019']
values = ['14', '4']
答案 0 :(得分:2)
一种简单的方法是创建一个默认字典,然后将其解包
from collections import defaultdict
result = defaultdict(float)
for label, value in zip(labels, values):
result[label] += float(value)
labels, values = zip(*result.items())
答案 1 :(得分:2)
您可以使用itertools.groupby
将两个压缩在一起的列表分组,并在values
中添加具有共同labels
的元素:
from itertools import groupby
from operator import itemgetter
z = zip(labels,values)
r = [(k, sum(int(i[1]) for i in v)) for k,v in groupby(z, key=itemgetter(0))]
labels, values = map(list, zip(*r))
print(labels)
# ['05/Feb/2019', '01/Feb/2019']
print(values)
# [14, 4]
答案 2 :(得分:1)
您可以使用transform-style: preserve-3d;
-webkit-transform-style: preserve-3d;
:
Counter