Search code examples
pythondatabaseliststatisticstuples

Need help combining the same element of a list of tuples in python


I have a single list from a database that is returning the information of a baseball stat across two days.

So say I have these 3 items in a single list of tuples:

("John Doe", 2, 3)
("Sponge Bob", 4, 5)
("John Doe", 1, 5)

How can I ONLY combine the two tuples of "John Doe" and add the two following values.

I am expecting to see:

("John Doe", 3, 8)
("Sponge Bob", 4, 5)

Solution

  • Here's another solution involving a temporary dictionary to group tuples with the same name, and numpy to ease the summing:

    import numpy as np
    
    my_tup=[
        ("John Doe", 2, 3),
        ("Sponge Bob", 4, 5),
        ("John Doe", 1, 5),
        ]
    
    my_dict = {}
    
    for tup in my_tup:
        my_dict.setdefault(tup[0], []).append(np.array(tup[1:]))
    
    grouped_tup = [(name, *sum(tup_list)) for name, tup_list in my_dict.items()]
    

    Output:

    grouped_tup
    [
       ('John Doe', 3, 8), 
       ('Sponge Bob', 4, 5)
    ]