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

Viewed 23

Title got confusing so heres an example. I have this list of tuples:

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

I need to change it in order for it to become :

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

Obviously the code needs to work for big lists with many duplicates, heres what I have so far:

    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)

My issue is that the outer while only completes once and I have no clue why. Any help appreciated. Note: This is my first day of writing python so if the code is abysmally wrong I'm sorry in advance.

2 Answers

Try:

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

Prints:

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

In terms of the bug fixes that are required to the original algorithm:

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