我有一个元组列表:
[ (a,1), (a,2), (b,1), (b,3) ]
我希望获得a
和b
值的总和。结果应采用以下格式:
[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ]
我该怎么做?
答案 0 :(得分:1)
from itertools import groupby
[{'key': k, 'value': sum(v for _,v in g)} for k, g in groupby(sorted(lst), key = lambda x: x[0])]
# [{'key': 'a', 'value': 3}, {'key': 'b', 'value': 4}]
答案 1 :(得分:1)
from collections import defaultdict
lst = [("a", 1), ("a", 2), ("b", 1), ("b", 3)]
out = defaultdict(list)
[out[v[0]].append(v[1]) for v in lst]
out = [{"key": k, "value": sum(v)} for k, v in out.iteritems()]
print out
答案 2 :(得分:1)
您可以使用collections.Counter
从初始列表中创建multiset,然后根据您的情况修改结果:
from collections import Counter
lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
part = sum((Counter({i[0]: i[1]}) for i in lst), Counter())
# Counter({'b': 4, 'a': 3})
final = [{'key': k, 'value': v} for k, v in part.items()]
# [{'key': 'b', 'value': 4}, {'key': 'a', 'value': 3}]
答案 3 :(得分:1)
与已经给出的答案非常相似。稍微长一点,但更容易阅读,恕我直言。
from collections import defaultdict
lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
dd = defaultdict(int)
for name, value in lst:
dd[name] += value
final = [{'key': k, 'value': v} for k, v in dd.items()]
(从Moses Koledoye的回答复制的最后一行)
答案 4 :(得分:0)
from collections import Counter
a = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
c = Counter()
for tup in a:
c = c + Counter(dict([tup]))