# Make a new list depending on group number and add scores up as well

• A+
Category：Languages

If a have a list within a another list that looks like this...

``[['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]] ``

How can I add the middle element together so so for 'Harry' for example, it shows up as `['Harry', 26]` and also for Python to look at the group number (3rd element) and output the winner only (the one with the highest score which is the middle element). So for each group, there needs to be one winner. So the final output shows:

``[['Harry', 26],['Sam',21]] ``

THIS QUESTION IS NOT A DUPLICATE: It has a third element as well which I am stuck about

The similar question gave me an answer of:

``grouped_scores = {} for name, score, group_number in players_info:     if name not in grouped_scores:         grouped_scores[name] = score         grouped_scores[group_number] = group_number      else:         grouped_scores[name] += score ``

I had thought doing something like this, but I'm not sure exactly what to do...

``grouped_scores = {} for name, score, group_number in players_info:     if name not in grouped_scores:         grouped_scores[name] = score     else:         grouped_scores[name] += score     for group in group_number:         if grouped_scores[group_number] = group_number:             [don't know what to do here] ``

Use `itertools.groupby`, and `collections.defaultdict`:

``l=[['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]] from itertools import groupby from collections import defaultdict l2=[list(y) for x,y in groupby(l,key=lambda x: x[-1])] l3=[] for x in l2:     d=defaultdict(int)     for x,y,z in x:        d[x]+=y     l3.append(max(list(map(list,dict(d).items())),key=lambda x: x[-1])) ``

Now:

``print(l3) ``

Is:

``[['Harry', 26], ['Sam', 21]] ``