繁体   English   中英

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

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

我遇到的问题与“使用Python对元组中每个给定的第一个值在元组中的第二个值求和”和“如何在Python中元组列表中对每个元组中的第一个值求和”有关? 主题,但我无法从他们那里提取问题的解决方案。 我想对每个元组的第三项求和,在元组的第一项和第二项中包含相同的模式。 可以说,有一个包含整数的数组,描述了x轴的bin位置。 此外,还有一个包含整数的数组,描述了y轴的bin数。 第三个数组包含相应的“重量”。

假使,假设

    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]

如上所述,我想对所有元组的第三个条目求和,如果前两个条目相同,则在这种情况下“描述2D空间中的相同位置”,因此,输出应为以下三个n个元组:

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

如何实现呢? 谢谢您,最好的问候,马克

Counter s是为此目的(主要是); 他们使计数变得简单:

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的好处是可以清楚地表明您正在计算事物-并且使用旨在执行此操作的标准类。 此外,通常,您最终可能会使用计数器的特殊功能。 出于所有这些原因,我建议您在defaultdict(int)使用Counter (即使它是某种不太穷人的Counter )。

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})

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

同时标记已经使用过的。

@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]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM