![](/img/trans.png)
[英]Python - List of Tuples, sum of tuples having same first value in this case?
[英]How to sum up a list of tuples having the same first element?
我有一个元组列表,例如:
(1,3)
(1,2)
(1,7)
(2,4)
(2,10)
(3,8)
我需要能够根据第一个值来总结第二个值,得到示例列表的结果:
(1,12)
(2,14)
(3,8)
这个问题在性质上与此问题非常相似,但是,我的解决方案可能不使用任何导入或for循环,并且该问题的所有答案都使用其中一个。 它应该依赖于列表和设置理解。
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]
我猜。 ......这些要求对这个问题不是很好(这个解决方案会很慢......)
如果您使用的是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:])]
输出:
In [10]: print(sums(l))
[(1, 12), (2, 14), (3, 8)]
对于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)]
相同的输出:
In [12]: print(sums(l))
[(1, 12), (2, 14), (3, 8)]
如果您可以使用词典,则以下内容应该有效
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()))
这非常简单,但绝对是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)
输出是
[(1, 12), (2, 14), (3, 8)]
我使用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()))
如果你需要使用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.