[英]How to sum up a list of tuples having the same first element?
I have a list of tuples, for example: 我有一个元组列表,例如:
(1,3)
(1,2)
(1,7)
(2,4)
(2,10)
(3,8)
I need to be able to sum up the second values based upon what the first value is, getting this result for the example list: 我需要能够根据第一个值来总结第二个值,得到示例列表的结果:
(1,12)
(2,14)
(3,8)
This question is very similar in nature to this one, however, my solution may not use any imports or for loops, and all answers to that question use one or the other. 这个问题在性质上与此问题非常相似,但是,我的解决方案可能不使用任何导入或for循环,并且该问题的所有答案都使用其中一个。 It's supposed to rely on list and set comprehension. 它应该依赖于列表和设置理解。
my_set = {x[0] for x in my_tuples}
my_sums = [(i,sum(x[1] for x in my_tuples if x[0] == i)) for i in my_set]
I guess. 我猜。 ... those requirements are not very good for this problem (this solution will be slow ...) ......这些要求对这个问题不是很好(这个解决方案会很慢......)
If you are using python2, you can use map to behave like izip_longest
and get the index of where the groups end: 如果您使用的是python2,则可以使用map来表现为izip_longest
并获取组结束位置的索引:
def sums(l):
st = set()
inds = [st.add(a) or ind for ind, (a, b) in enumerate(l) if a not in st]
return [(l[i][0], sum(sub[1] for sub in l[i:j])) for i, j in map(None, inds, inds[1:])]
Output: 输出:
In [10]: print(sums(l))
[(1, 12), (2, 14), (3, 8)]
for python 2 or 3 you can just use enumerate and check the index: 对于python 2或3,您可以使用枚举并检查索引:
def sums(l):
st = set()
inds = [st.add(a) or ind for ind, (a, b) in enumerate(l) if a not in st]
return [(l[j][0], sum(sub[1] for sub in (l[j:inds[i]] if i < len(inds) else l[inds[-1]:])))
for i, j in enumerate(inds, 1)]
same output: 相同的输出:
In [12]: print(sums(l))
[(1, 12), (2, 14), (3, 8)]
If you can use dictionaries the following should work 如果您可以使用词典,则以下内容应该有效
x = [(1,3), (1, 2), (1, 7), (2, 4), (2, 10), (3, 8)]
d = {}
[d.__setitem__(first, d.get(first, 0) + second) for first, second in x]
print(list(d.items()))
This is pretty straightforward, but it's definitely O(n**2), so keep your input data small: 这非常简单,但绝对是O(n ** 2),所以要保持输入数据小:
data = (
(1,3),
(1,2),
(1,7),
(2,4),
(2,10),
(3,8),
)
d = { k:v for k,v in data }
d2 = [(t1,sum( v for k,v in data if k == t1 )) for t1 in d.keys() ]
print(d2)
Output is 输出是
[(1, 12), (2, 14), (3, 8)]
I'd use a defaultdict 我使用defaultdict
from collections import defaultdict
x = [(1,3), (1, 2), (1, 7), (2, 4), (2, 10), (3, 8)]
d = defaultdict(int)
for k, v in x:
d[k] += v
print(list(d.items()))
if you need a one-liner (lambda inline function) using itertools 如果你需要使用itertools的单行(lambda内联函数)
from itertools import groupby
myfunc = lambda tu : [(k, sum(v2[1] for v2 in v)) for k, v in groupby(tu, lambda x: x[0])])
print(myfunc(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.