简体   繁体   English

如何总结具有相同第一元素的元组列表?

[英]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.

相关问题 Python - 元组列表,在这种情况下具有相同第一个值的元组的总和? - Python - List of Tuples, sum of tuples having same first value in this case? 如何总结具有多个条件的元组列表中的最后一个数字/元素? - How to sum-up the last number/element in the list of tuples having multiple criteria? 如果元组具有相同的第一个元素,如何聚合元组列表的元素? - how to aggregate elements of a list of tuples if the tuples have the same first element? 如何对第一个值相同的列表中的元组求和? - How do I sum tuples in a list where the first value is the same? 元组列表中第一个索引为 1 而不是 0 的元素 - first element having the index of 1 instead of 0 in a list of tuples Python元组列表中第二个和第三个元素的和,按第一个分组 - Python sum of second and third element of tuple in list of tuples grouped by first 总结元组列表中相同项目的值,而它们是字符串 - To sum up values of same items in a list of tuples while they are string 如何按元组的第一个元素对元组列表进行排序? - How to sort a list of tuples by their first element? 如何按 Python 中的第一个元素重新分类元组列表? - How to recategorize a list of tuples by the first element in Python? 如何获取元组列表中的第一个元素? - How to get first element in a list of tuples?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM