Python – 2D list – find duplicates in one column and sum values in another column

  duplicates, list, python

I have a 2D list that contains soccer player names, the number of times they scored a goal, and the number of times they attempted a shot on goal, respectively.

player_stats = [['Adam', 5, 10], ['Kyle', 12, 18], ['Jo', 20, 35], ['Adam', 15, 20], ['Charlie', 31, 58], ['Jo', 6, 14], ['Adam', 10, 15]]

From this list, I’m trying to return another list that shows only one instance of each player with their respective total goals and total attempts on goal, like so:

player_stats_totals = [['Adam', 30, 45], ['Kyle', 12, 18], ['Jo', 26, 49], ['Charlie', 31, 58]]

After searching on Stack Overflow I was able to learn (from this thread) how to return the indexes of the duplicate players

x = [player_stats[i][0] for i in range (len(player_stats))]

for i in range (len(x)):
    if (x[i] in x[:i]) or (x[i] in x[i+1:]): print (x[i], i)

but got stuck on how to proceed thereafter and if indeed this method is strictly relevant for what I need(?)

What’s the most efficient way to return the desired list of totals?

Source: Python Questions