How to sum values of tuples that have same name in Python
我有下面的列表,其中包含必须值的元组:
1 | mylist=[(3, 'a'), (2, 'b'), (4, 'a'), (5, 'c'), (2, 'a'), (1, 'b')] |
有没有一种方法可以对所有共享同一名称的值求和?比如:
1 | (9, 'a'), (3, 'b'), (5, 'c') |
号
我尝试用for循环迭代元组,但无法得到我想要的。
谢谢你
使用dict(或defaultdict)对元组进行聚合:
1 2 3 4 5 6 7 8 9 10 11 12 | from collections import defaultdict mylist=[(3, 'a'), (2, 'b'), (4, 'a'), (5, 'c'), (2, 'a'), (1, 'b')] sums = defaultdict(int) for i, k in mylist: sums[k] += i print sums.items() # output: [('a', 9), ('c', 5), ('b', 3)] # Or if you want the key/value order reversed and sorted by key print [(v, k) for (k, v) in sorted(sums.items())] # output: [(9, 'a'), (3, 'b'), (5, 'c')] |
号
一种没有任何依赖关系的简单方法:
1 2 3 4 5 6 7 8 | mylist = [(3, 'a'), (2, 'b'), (4, 'a'), (5, 'c'), (2, 'a'), (1, 'b')] sums = {} for a, b in mylist: if b not in sums: sums[b] = a else: sums[b] += a print list(sums.items()) |
您可以创建一个具有单个键总和的
1 2 3 4 5 | >>> my_dict = {} >>> for item in mylist: ... my_dict[item[1]] = my_dict.get(item[1], 0) + item[0] >>> [(my_dict[k], k) for k in my_dict] [(9, 'a'), (5, 'c'), (3, 'b')] |
。
可以使用
1 2 3 | >>> import itertools >>> [(sum(i[0] for i in group), key) for key, group in itertools.groupby(sorted(mylist, key = lambda i: i[1]), lambda i: i[1])] [(9, 'a'), (3, 'b'), (5, 'c')] |