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











up vote
6
down vote

favorite












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


But that only adds the scores up, it doesn't take out the winner from each group. Please help.



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]









share|improve this question




























    up vote
    6
    down vote

    favorite












    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


    But that only adds the scores up, it doesn't take out the winner from each group. Please help.



    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]









    share|improve this question


























      up vote
      6
      down vote

      favorite









      up vote
      6
      down vote

      favorite











      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


      But that only adds the scores up, it doesn't take out the winner from each group. Please help.



      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]









      share|improve this question















      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


      But that only adds the scores up, it doesn't take out the winner from each group. Please help.



      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]






      python arrays python-3.x list






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 at 10:04









      U9-Forward

      9,6012833




      9,6012833










      asked Nov 14 at 8:03







      user10650570































          5 Answers
          5






          active

          oldest

          votes

















          up vote
          5
          down vote



          accepted










          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]]





          share|improve this answer

















          • 1




            Can you please just add in comments so I can learn and understand what each line is doing?
            – user10650570
            Nov 14 at 9:29








          • 1




            @Harry First two lines are importing modules, then next line is using groupby to separate in to two groups based on last element of each sub-list, next line to create empty list, next loop iterating trough the grouped ones, then create a defaultdict, then the sub-loop is adding the stuff to the defaultdict, then last line to manage how to make that dictionary into a list.
            – U9-Forward
            Nov 14 at 9:39










          • @Harry Happy to help, :-), 😊😊😊😊
            – U9-Forward
            Nov 14 at 9:39






          • 1




            Thank you more the help!!
            – user10650570
            Nov 14 at 9:47










          • @Harry YW. again. :D
            – U9-Forward
            Nov 14 at 10:05


















          up vote
          0
          down vote













          you can try to use Counter and it's method most_common




          Return a list of the n most common elements and their counts from the
          most common to the least




          from collections import Counter
          l = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
          step = 3
          results = list()
          for x in range(0, len(l), step):
          cnt = Counter()
          for y in l[x: x+step]:
          cnt.update({y[0]: y[1]})
          results.append(cnt.most_common(1)[0])


          will give you:



          print(results)
          [('Harry', 26), ('Sam', 21)]





          share|improve this answer






























            up vote
            0
            down vote













            I would aggregate the data first with a defaultdict.



            >>> from collections import defaultdict
            >>>
            >>> combined = defaultdict(lambda: defaultdict(int))
            >>> data = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
            >>>
            >>> for name, score, group in data:
            ...: combined[group][name] += score
            ...:
            >>> combined
            >>>
            defaultdict(<function __main__.<lambda>()>,
            {1: defaultdict(int, {'Harry': 26, 'Jake': 4}),
            2: defaultdict(int, {'Dave': 9, 'Sam': 21})})


            Then apply max to each value in that dict.



            >>> from operator import itemgetter
            >>> [list(max(v.items(), key=itemgetter(1))) for v in combined.values()]
            >>> [['Harry', 26], ['Sam', 21]]





            share|improve this answer




























              up vote
              0
              down vote













              use itertools.groupby and then take the middle value from the grouped element and then append it to a list passed on the maximum condition



              import itertools
              l=[['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
              maxlist=
              maxmiddleindexvalue=0
              for key,value in itertools.groupby(l,key=lambda x:x[0]):
              s=0
              m=0
              for element in value:
              s+=element[1]
              m=max(m,element[1])
              if(m==maxmiddleindexvalue):
              maxlist.append([(key,s)])

              if(m>maxmiddleindexvalue):
              maxlist=[(key,s)]
              maxmiddleindexvalue=m

              print(maxlist)


              OUTPUT



              [('Harry', 26), [('Sam', 21)]]





              share|improve this answer




























                up vote
                0
                down vote













                I created groups which hold every group's players (name and score) and extract the player with the highest score for every group:



                from collections import defaultdict

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

                # Divide the players into groups and calculate their score
                groups = defaultdict(lambda: defaultdict(int))
                for item in data:
                name, score, group = item[0], item[1], item[2]
                groups[group][name] += score

                # Find out who are the winners
                winners =
                for group in groups.values():
                # Take the player with highest score
                winner = list(max(group.iteritems(), key=lambda x: x[1]))
                winners.append(winner)

                print(winners) # >>> [['Harry', 26], ['Sam', 21]]





                share|improve this answer























                • Less readable IMO but winners calculation could be also shortened to: winners = [list(max(group.iteritems(), key=lambda x: x[1])) for group in groups.values()]
                  – Maor Refaeli
                  Nov 14 at 12:33











                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295489%2fmake-a-new-list-depending-on-group-number-and-add-scores-up-as-well%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown
























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                5
                down vote



                accepted










                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]]





                share|improve this answer

















                • 1




                  Can you please just add in comments so I can learn and understand what each line is doing?
                  – user10650570
                  Nov 14 at 9:29








                • 1




                  @Harry First two lines are importing modules, then next line is using groupby to separate in to two groups based on last element of each sub-list, next line to create empty list, next loop iterating trough the grouped ones, then create a defaultdict, then the sub-loop is adding the stuff to the defaultdict, then last line to manage how to make that dictionary into a list.
                  – U9-Forward
                  Nov 14 at 9:39










                • @Harry Happy to help, :-), 😊😊😊😊
                  – U9-Forward
                  Nov 14 at 9:39






                • 1




                  Thank you more the help!!
                  – user10650570
                  Nov 14 at 9:47










                • @Harry YW. again. :D
                  – U9-Forward
                  Nov 14 at 10:05















                up vote
                5
                down vote



                accepted










                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]]





                share|improve this answer

















                • 1




                  Can you please just add in comments so I can learn and understand what each line is doing?
                  – user10650570
                  Nov 14 at 9:29








                • 1




                  @Harry First two lines are importing modules, then next line is using groupby to separate in to two groups based on last element of each sub-list, next line to create empty list, next loop iterating trough the grouped ones, then create a defaultdict, then the sub-loop is adding the stuff to the defaultdict, then last line to manage how to make that dictionary into a list.
                  – U9-Forward
                  Nov 14 at 9:39










                • @Harry Happy to help, :-), 😊😊😊😊
                  – U9-Forward
                  Nov 14 at 9:39






                • 1




                  Thank you more the help!!
                  – user10650570
                  Nov 14 at 9:47










                • @Harry YW. again. :D
                  – U9-Forward
                  Nov 14 at 10:05













                up vote
                5
                down vote



                accepted







                up vote
                5
                down vote



                accepted






                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]]





                share|improve this answer












                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]]






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 at 8:18









                U9-Forward

                9,6012833




                9,6012833








                • 1




                  Can you please just add in comments so I can learn and understand what each line is doing?
                  – user10650570
                  Nov 14 at 9:29








                • 1




                  @Harry First two lines are importing modules, then next line is using groupby to separate in to two groups based on last element of each sub-list, next line to create empty list, next loop iterating trough the grouped ones, then create a defaultdict, then the sub-loop is adding the stuff to the defaultdict, then last line to manage how to make that dictionary into a list.
                  – U9-Forward
                  Nov 14 at 9:39










                • @Harry Happy to help, :-), 😊😊😊😊
                  – U9-Forward
                  Nov 14 at 9:39






                • 1




                  Thank you more the help!!
                  – user10650570
                  Nov 14 at 9:47










                • @Harry YW. again. :D
                  – U9-Forward
                  Nov 14 at 10:05














                • 1




                  Can you please just add in comments so I can learn and understand what each line is doing?
                  – user10650570
                  Nov 14 at 9:29








                • 1




                  @Harry First two lines are importing modules, then next line is using groupby to separate in to two groups based on last element of each sub-list, next line to create empty list, next loop iterating trough the grouped ones, then create a defaultdict, then the sub-loop is adding the stuff to the defaultdict, then last line to manage how to make that dictionary into a list.
                  – U9-Forward
                  Nov 14 at 9:39










                • @Harry Happy to help, :-), 😊😊😊😊
                  – U9-Forward
                  Nov 14 at 9:39






                • 1




                  Thank you more the help!!
                  – user10650570
                  Nov 14 at 9:47










                • @Harry YW. again. :D
                  – U9-Forward
                  Nov 14 at 10:05








                1




                1




                Can you please just add in comments so I can learn and understand what each line is doing?
                – user10650570
                Nov 14 at 9:29






                Can you please just add in comments so I can learn and understand what each line is doing?
                – user10650570
                Nov 14 at 9:29






                1




                1




                @Harry First two lines are importing modules, then next line is using groupby to separate in to two groups based on last element of each sub-list, next line to create empty list, next loop iterating trough the grouped ones, then create a defaultdict, then the sub-loop is adding the stuff to the defaultdict, then last line to manage how to make that dictionary into a list.
                – U9-Forward
                Nov 14 at 9:39




                @Harry First two lines are importing modules, then next line is using groupby to separate in to two groups based on last element of each sub-list, next line to create empty list, next loop iterating trough the grouped ones, then create a defaultdict, then the sub-loop is adding the stuff to the defaultdict, then last line to manage how to make that dictionary into a list.
                – U9-Forward
                Nov 14 at 9:39












                @Harry Happy to help, :-), 😊😊😊😊
                – U9-Forward
                Nov 14 at 9:39




                @Harry Happy to help, :-), 😊😊😊😊
                – U9-Forward
                Nov 14 at 9:39




                1




                1




                Thank you more the help!!
                – user10650570
                Nov 14 at 9:47




                Thank you more the help!!
                – user10650570
                Nov 14 at 9:47












                @Harry YW. again. :D
                – U9-Forward
                Nov 14 at 10:05




                @Harry YW. again. :D
                – U9-Forward
                Nov 14 at 10:05












                up vote
                0
                down vote













                you can try to use Counter and it's method most_common




                Return a list of the n most common elements and their counts from the
                most common to the least




                from collections import Counter
                l = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                step = 3
                results = list()
                for x in range(0, len(l), step):
                cnt = Counter()
                for y in l[x: x+step]:
                cnt.update({y[0]: y[1]})
                results.append(cnt.most_common(1)[0])


                will give you:



                print(results)
                [('Harry', 26), ('Sam', 21)]





                share|improve this answer



























                  up vote
                  0
                  down vote













                  you can try to use Counter and it's method most_common




                  Return a list of the n most common elements and their counts from the
                  most common to the least




                  from collections import Counter
                  l = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                  step = 3
                  results = list()
                  for x in range(0, len(l), step):
                  cnt = Counter()
                  for y in l[x: x+step]:
                  cnt.update({y[0]: y[1]})
                  results.append(cnt.most_common(1)[0])


                  will give you:



                  print(results)
                  [('Harry', 26), ('Sam', 21)]





                  share|improve this answer

























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    you can try to use Counter and it's method most_common




                    Return a list of the n most common elements and their counts from the
                    most common to the least




                    from collections import Counter
                    l = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                    step = 3
                    results = list()
                    for x in range(0, len(l), step):
                    cnt = Counter()
                    for y in l[x: x+step]:
                    cnt.update({y[0]: y[1]})
                    results.append(cnt.most_common(1)[0])


                    will give you:



                    print(results)
                    [('Harry', 26), ('Sam', 21)]





                    share|improve this answer














                    you can try to use Counter and it's method most_common




                    Return a list of the n most common elements and their counts from the
                    most common to the least




                    from collections import Counter
                    l = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                    step = 3
                    results = list()
                    for x in range(0, len(l), step):
                    cnt = Counter()
                    for y in l[x: x+step]:
                    cnt.update({y[0]: y[1]})
                    results.append(cnt.most_common(1)[0])


                    will give you:



                    print(results)
                    [('Harry', 26), ('Sam', 21)]






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 14 at 8:24

























                    answered Nov 14 at 8:18









                    Bear Brown

                    11.3k81839




                    11.3k81839






















                        up vote
                        0
                        down vote













                        I would aggregate the data first with a defaultdict.



                        >>> from collections import defaultdict
                        >>>
                        >>> combined = defaultdict(lambda: defaultdict(int))
                        >>> data = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                        >>>
                        >>> for name, score, group in data:
                        ...: combined[group][name] += score
                        ...:
                        >>> combined
                        >>>
                        defaultdict(<function __main__.<lambda>()>,
                        {1: defaultdict(int, {'Harry': 26, 'Jake': 4}),
                        2: defaultdict(int, {'Dave': 9, 'Sam': 21})})


                        Then apply max to each value in that dict.



                        >>> from operator import itemgetter
                        >>> [list(max(v.items(), key=itemgetter(1))) for v in combined.values()]
                        >>> [['Harry', 26], ['Sam', 21]]





                        share|improve this answer

























                          up vote
                          0
                          down vote













                          I would aggregate the data first with a defaultdict.



                          >>> from collections import defaultdict
                          >>>
                          >>> combined = defaultdict(lambda: defaultdict(int))
                          >>> data = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                          >>>
                          >>> for name, score, group in data:
                          ...: combined[group][name] += score
                          ...:
                          >>> combined
                          >>>
                          defaultdict(<function __main__.<lambda>()>,
                          {1: defaultdict(int, {'Harry': 26, 'Jake': 4}),
                          2: defaultdict(int, {'Dave': 9, 'Sam': 21})})


                          Then apply max to each value in that dict.



                          >>> from operator import itemgetter
                          >>> [list(max(v.items(), key=itemgetter(1))) for v in combined.values()]
                          >>> [['Harry', 26], ['Sam', 21]]





                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            I would aggregate the data first with a defaultdict.



                            >>> from collections import defaultdict
                            >>>
                            >>> combined = defaultdict(lambda: defaultdict(int))
                            >>> data = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                            >>>
                            >>> for name, score, group in data:
                            ...: combined[group][name] += score
                            ...:
                            >>> combined
                            >>>
                            defaultdict(<function __main__.<lambda>()>,
                            {1: defaultdict(int, {'Harry': 26, 'Jake': 4}),
                            2: defaultdict(int, {'Dave': 9, 'Sam': 21})})


                            Then apply max to each value in that dict.



                            >>> from operator import itemgetter
                            >>> [list(max(v.items(), key=itemgetter(1))) for v in combined.values()]
                            >>> [['Harry', 26], ['Sam', 21]]





                            share|improve this answer












                            I would aggregate the data first with a defaultdict.



                            >>> from collections import defaultdict
                            >>>
                            >>> combined = defaultdict(lambda: defaultdict(int))
                            >>> data = [['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                            >>>
                            >>> for name, score, group in data:
                            ...: combined[group][name] += score
                            ...:
                            >>> combined
                            >>>
                            defaultdict(<function __main__.<lambda>()>,
                            {1: defaultdict(int, {'Harry': 26, 'Jake': 4}),
                            2: defaultdict(int, {'Dave': 9, 'Sam': 21})})


                            Then apply max to each value in that dict.



                            >>> from operator import itemgetter
                            >>> [list(max(v.items(), key=itemgetter(1))) for v in combined.values()]
                            >>> [['Harry', 26], ['Sam', 21]]






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 14 at 8:24









                            timgeb

                            44.3k106185




                            44.3k106185






















                                up vote
                                0
                                down vote













                                use itertools.groupby and then take the middle value from the grouped element and then append it to a list passed on the maximum condition



                                import itertools
                                l=[['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                                maxlist=
                                maxmiddleindexvalue=0
                                for key,value in itertools.groupby(l,key=lambda x:x[0]):
                                s=0
                                m=0
                                for element in value:
                                s+=element[1]
                                m=max(m,element[1])
                                if(m==maxmiddleindexvalue):
                                maxlist.append([(key,s)])

                                if(m>maxmiddleindexvalue):
                                maxlist=[(key,s)]
                                maxmiddleindexvalue=m

                                print(maxlist)


                                OUTPUT



                                [('Harry', 26), [('Sam', 21)]]





                                share|improve this answer

























                                  up vote
                                  0
                                  down vote













                                  use itertools.groupby and then take the middle value from the grouped element and then append it to a list passed on the maximum condition



                                  import itertools
                                  l=[['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                                  maxlist=
                                  maxmiddleindexvalue=0
                                  for key,value in itertools.groupby(l,key=lambda x:x[0]):
                                  s=0
                                  m=0
                                  for element in value:
                                  s+=element[1]
                                  m=max(m,element[1])
                                  if(m==maxmiddleindexvalue):
                                  maxlist.append([(key,s)])

                                  if(m>maxmiddleindexvalue):
                                  maxlist=[(key,s)]
                                  maxmiddleindexvalue=m

                                  print(maxlist)


                                  OUTPUT



                                  [('Harry', 26), [('Sam', 21)]]





                                  share|improve this answer























                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    use itertools.groupby and then take the middle value from the grouped element and then append it to a list passed on the maximum condition



                                    import itertools
                                    l=[['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                                    maxlist=
                                    maxmiddleindexvalue=0
                                    for key,value in itertools.groupby(l,key=lambda x:x[0]):
                                    s=0
                                    m=0
                                    for element in value:
                                    s+=element[1]
                                    m=max(m,element[1])
                                    if(m==maxmiddleindexvalue):
                                    maxlist.append([(key,s)])

                                    if(m>maxmiddleindexvalue):
                                    maxlist=[(key,s)]
                                    maxmiddleindexvalue=m

                                    print(maxlist)


                                    OUTPUT



                                    [('Harry', 26), [('Sam', 21)]]





                                    share|improve this answer












                                    use itertools.groupby and then take the middle value from the grouped element and then append it to a list passed on the maximum condition



                                    import itertools
                                    l=[['Harry',9,1],['Harry',17,1],['Jake',4,1], ['Dave',9,2],['Sam',17,2],['Sam',4,2]]
                                    maxlist=
                                    maxmiddleindexvalue=0
                                    for key,value in itertools.groupby(l,key=lambda x:x[0]):
                                    s=0
                                    m=0
                                    for element in value:
                                    s+=element[1]
                                    m=max(m,element[1])
                                    if(m==maxmiddleindexvalue):
                                    maxlist.append([(key,s)])

                                    if(m>maxmiddleindexvalue):
                                    maxlist=[(key,s)]
                                    maxmiddleindexvalue=m

                                    print(maxlist)


                                    OUTPUT



                                    [('Harry', 26), [('Sam', 21)]]






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 14 at 8:29









                                    Albin Paul

                                    1,285617




                                    1,285617






















                                        up vote
                                        0
                                        down vote













                                        I created groups which hold every group's players (name and score) and extract the player with the highest score for every group:



                                        from collections import defaultdict

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

                                        # Divide the players into groups and calculate their score
                                        groups = defaultdict(lambda: defaultdict(int))
                                        for item in data:
                                        name, score, group = item[0], item[1], item[2]
                                        groups[group][name] += score

                                        # Find out who are the winners
                                        winners =
                                        for group in groups.values():
                                        # Take the player with highest score
                                        winner = list(max(group.iteritems(), key=lambda x: x[1]))
                                        winners.append(winner)

                                        print(winners) # >>> [['Harry', 26], ['Sam', 21]]





                                        share|improve this answer























                                        • Less readable IMO but winners calculation could be also shortened to: winners = [list(max(group.iteritems(), key=lambda x: x[1])) for group in groups.values()]
                                          – Maor Refaeli
                                          Nov 14 at 12:33















                                        up vote
                                        0
                                        down vote













                                        I created groups which hold every group's players (name and score) and extract the player with the highest score for every group:



                                        from collections import defaultdict

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

                                        # Divide the players into groups and calculate their score
                                        groups = defaultdict(lambda: defaultdict(int))
                                        for item in data:
                                        name, score, group = item[0], item[1], item[2]
                                        groups[group][name] += score

                                        # Find out who are the winners
                                        winners =
                                        for group in groups.values():
                                        # Take the player with highest score
                                        winner = list(max(group.iteritems(), key=lambda x: x[1]))
                                        winners.append(winner)

                                        print(winners) # >>> [['Harry', 26], ['Sam', 21]]





                                        share|improve this answer























                                        • Less readable IMO but winners calculation could be also shortened to: winners = [list(max(group.iteritems(), key=lambda x: x[1])) for group in groups.values()]
                                          – Maor Refaeli
                                          Nov 14 at 12:33













                                        up vote
                                        0
                                        down vote










                                        up vote
                                        0
                                        down vote









                                        I created groups which hold every group's players (name and score) and extract the player with the highest score for every group:



                                        from collections import defaultdict

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

                                        # Divide the players into groups and calculate their score
                                        groups = defaultdict(lambda: defaultdict(int))
                                        for item in data:
                                        name, score, group = item[0], item[1], item[2]
                                        groups[group][name] += score

                                        # Find out who are the winners
                                        winners =
                                        for group in groups.values():
                                        # Take the player with highest score
                                        winner = list(max(group.iteritems(), key=lambda x: x[1]))
                                        winners.append(winner)

                                        print(winners) # >>> [['Harry', 26], ['Sam', 21]]





                                        share|improve this answer














                                        I created groups which hold every group's players (name and score) and extract the player with the highest score for every group:



                                        from collections import defaultdict

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

                                        # Divide the players into groups and calculate their score
                                        groups = defaultdict(lambda: defaultdict(int))
                                        for item in data:
                                        name, score, group = item[0], item[1], item[2]
                                        groups[group][name] += score

                                        # Find out who are the winners
                                        winners =
                                        for group in groups.values():
                                        # Take the player with highest score
                                        winner = list(max(group.iteritems(), key=lambda x: x[1]))
                                        winners.append(winner)

                                        print(winners) # >>> [['Harry', 26], ['Sam', 21]]






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Nov 14 at 8:41

























                                        answered Nov 14 at 8:27









                                        Maor Refaeli

                                        1,1751725




                                        1,1751725












                                        • Less readable IMO but winners calculation could be also shortened to: winners = [list(max(group.iteritems(), key=lambda x: x[1])) for group in groups.values()]
                                          – Maor Refaeli
                                          Nov 14 at 12:33


















                                        • Less readable IMO but winners calculation could be also shortened to: winners = [list(max(group.iteritems(), key=lambda x: x[1])) for group in groups.values()]
                                          – Maor Refaeli
                                          Nov 14 at 12:33
















                                        Less readable IMO but winners calculation could be also shortened to: winners = [list(max(group.iteritems(), key=lambda x: x[1])) for group in groups.values()]
                                        – Maor Refaeli
                                        Nov 14 at 12:33




                                        Less readable IMO but winners calculation could be also shortened to: winners = [list(max(group.iteritems(), key=lambda x: x[1])) for group in groups.values()]
                                        – Maor Refaeli
                                        Nov 14 at 12:33


















                                         

                                        draft saved


                                        draft discarded



















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295489%2fmake-a-new-list-depending-on-group-number-and-add-scores-up-as-well%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Probability when a professor distributes a quiz and homework assignment to a class of n students.

                                        Aardman Animations

                                        Are they similar matrix