首页 > 解决方案 > 如何对元组求和?因为原始总和将它们连接起来

问题描述

我有一个很大的字典,我正在其中扫描一个 API,并根据曲棍球比赛中的投篮是否是目标来添加值。这是我现在的代码...

for key in contents['liveData']['plays']['allPlays']:
        # for plays in key['result']['event']:
            # print(key)
        if (key['result']['event'] == "Shot"):
            #print(key['result']['event'])
            scoordinates = (key['coordinates']['x'], key['coordinates']['y'])
            if scoordinates not in shots:
                shots[scoordinates] = (1, 0)
            else:
                shots[scoordinates] += (1, 0)
        if (key['result']['event'] == "Goal"):
            #print(key['result']['event'])
            gcoordinates = (key['coordinates']['x'], key['coordinates']['y'])
            if gcoordinates not in shots:
                shots[gcoordinates] = (1, 1)
            else:
                shots[gcoordinates] += (1, 1) 

我试图通过使用括号向字典添加两个值,但这不起作用,因为每当有重复的坐标拍摄时,表格都会添加这样的值 (1,0, 1, 1) 而不是 (2 ,1)。这可能吗?我在想这里可能有一个简单的格式修复,但我不完全确定。

标签: pythonapidictionaryfor-loopkey

解决方案


您可以使用 sum 代替 +=:

a = tuple(map(sum, zip(a, b)))

因此,对于这种情况,请使用:

shots[gcoordinates] = tuple(map(sum, zip((1, 1), shots[gcoordinates])))

推荐阅读