元组列表,删除具有相同第一项的那些,但使剩余副本的第三项成为第三项的总和

List of tuples, remove the ones with same 1st item but make the remaining copy's 3rd item the sum of both 3rd items

标题令人困惑所以这是一个例子。我有这个元组列表:

results = [(3941, 'Athens El. Venizelos', 2), (1472, 'Rhodes Diagoras', 1), (3941, 'Athens El. Venizelos', 11)]

我需要将其更改为:

results = [(3941, 'Athens El. Venizelos', 13), (1472, 'Rhodes Diagoras', 1)]

显然代码需要适用于有很多重复的大列表,这是我目前所拥有的:

    i = 0
    j = 0
    while i<len(results):
        temp1 = results[i]
        while j<len(results):
            temp2 = results[j]
            if temp1[0] == temp2[0] and i!=j:
                temp1 = list(temp1)
                temp1[2] = temp1[2]+temp2[2]
                temp1 = tuple(temp1)
                del results[j]
            j+=1
        i+=1       
    print(results)

我的问题是外部 while 只完成一次,我不知道为什么。任何帮助表示赞赏。注意:这是我第一天写 python 所以如果代码有错我提前道歉。

尝试:

results = [
    (3941, "Athens El. Venizelos", 2),
    (1472, "Rhodes Diagoras", 1),
    (3941, "Athens El. Venizelos", 11),
]

tmp = {}
for a, b, c in results:
    tmp[a] = a, b, c + tmp.get(a, (None, None, 0))[2]

print(list(tmp.values()))

打印:

[(3941, 'Athens El. Venizelos', 13), (1472, 'Rhodes Diagoras', 1)]

原算法需要修复的bug:

i = 0
while i<len(results):
    temp1 = results[i]
    j = 0                     # <=== this needs to be inside the outer loop
    while j<len(results):
        temp2 = results[j]
        if temp1[0] == temp2[0] and i!=j:
            temp1 = list(temp1)
            temp1[2] = temp1[2]+temp2[2]
            results[i] = tuple(temp1)    # <=== need to assign back into results[i]
            del results[j]
        j+=1
    i+=1       
print(results)