使用 Python 对元组中前两个值的给定对求和元组中的第三个值

Sum third value in tuple for a given pair of the first two values in the tuple using Python

我的问题与 "Sum second value in tuple for each given first value in tuples using Python" 和 "How do I sum the first value in each tuple in a list of tuples in Python?" 主题有关,但我无法从中提取问题的解决方案。 我想对每个元组的第三个条目求和,它在元组的第一个和第二个条目中包含相同的模式。 比方说,有一个包含整数的数组,描述了 x 轴的 bin 位置。此外,还有一个包含整数的数组,描述了 y 轴的二进制数。第三个数组包含对应的"weigths".

假设

    ix = [0,1,2,0,1] and 
    iy = [0,1,1,0,1] and 
    w = [1,2,3,4,5]

我用 "zip" 从这些数组创建了元组,导致:

    [0,0,1]
    [1,1,2]
    [2,1,3]
    [0,0,4]
    [1,1,5]

如上所述,如果前两个条目相同,我想对所有元组的第三个条目求和,在这种情况下 "describing the same position in an 2D-space" 因此,输出应该是以下三个n元组:

    [0,0,5]
    [1,1,7]
    [2,1,3] 

如何实现? 谢谢你和最好的问候,马克

遍历数组并比较第一个和第二个值,如果相等则相加。

也标出已经使用过的。

@EOL感谢评论。

arrays = [[0, 0, 1], [1, 1, 2], [2, 1, 3], [0, 0, 4], [1, 1, 5]]
new = []

for i,a in enumerate(arrays):
    for j,b in enumerate(arrays[i+1:]):
        if a[0] == b[0] and a[1] == b[1]:
            #print a,b,(a[2] + b[2])
            a.append('added')
            b.append('added')
            new.append([a[0],a[1],a[2] + b[2]])
    if 'added' not in a:
        new.append(a)

print new

输出

[[0, 0, 5], [1, 1, 7], [2, 1, 3]]

defaultdict 很好地满足了您的需求:

>>> from collections import defaultdict
>>> res = defaultdict(int)
>>> for p in zip(w, *[ix, iy]):
        res[p[1:]] += p[0]
defaultdict(<type 'int'>, {(0, 0): 5, (1, 1): 7, (2, 1): 3})

Counters 是为了这个(大部分);他们使计数变得简单:

from collections import Counter

ix = [0,1,2,0,1]
iy = [0,1,1,0,1]
w = [1,2,3,4,5]

counts = Counter()
for (key, count) in zip(zip(ix, iy), w):
    counts[key] += count
print "Counts:", counts

counts_as_list = [  # Conversion of the counting result (counts) to a list
    [key[0], key[1], total_count] for (key, total_count) in counts.iteritems()]    
print "As a list:", counts_as_list

给予

Counts: Counter({(1, 1): 7, (0, 0): 5, (2, 1): 3})
As a list: [[0, 0, 5], [1, 1, 7], [2, 1, 3]]

PS:ferhat elmas 的 collections.defaultdict(int) 解决方案也很好。然而,使用像上面那样的 Counter 的好处是可以明确表示您正在计算事物——并且使用标准的 class 旨在做到这一点。此外,一般来说,您最终可能会使用计数器的特殊功能。出于所有这些原因,我确实建议使用 Counter 而不是 defaultdict(int)(即使它是某种不那么穷人的 Counter)。