working out the average within a nested list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PythonB15
    New Member
    • May 2015
    • 7

    working out the average within a nested list

    Hi all,

    another question....

    I have a data structure which consists of a game players name and their scores, I have use lists within lists (2D):

    results = [["Ben", 15, 18,25], ["George", 25, 35, 85], ["Evie", 2, 54, 84]]

    What I want to do is work out the average for each player and then sort by the highest average score.

    any idea?

    Thanks in advance
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Calculate it for each item in the list and create a 2nd list with the average as the first sub-item.
    Code:
    test_list=[[20, "Ben", 15, 18,25], [50, "George", 25, 35, 85], [19, "Evie", 2, 54, 84]]
    test_list.sort
    print test_list

    Comment

    • computerfox
      Contributor
      • Mar 2010
      • 276

      #3
      Code:
      #!/bin/python
      results = [["Ben", 15, 18,25], ["George", 25, 35, 85], ["Evie", 2, 54, 84]];
      i=0;
      while i < len(results):
       j=1;
       scores=[];
       while j < 4:
        scores.append(results[i][j]);
        j+=1;
       scores.sort();
       print results[i][0]+": "+str(scores[2])+","+str(scores[1])+","+str(scores[0]);
       i+=1;

      Comment

      • PythonB15
        New Member
        • May 2015
        • 7

        #4
        dwblas, you said calculate it for each item, how would you actually do this in python?

        computerfox, thanks for the solution is this the most effective way to get an average in Python?

        Comment

        • computerfox
          Contributor
          • Mar 2010
          • 276

          #5
          The scores that you gave, are those the scores and you want to get the average for each player?
          For example, for Ben, 15+18+25/3=19.33 .

          In that case, it should be:
          Code:
          #!/bin/python
          results = [["Ben", 15, 18,25], ["George", 25, 35, 85], ["Evie", 2, 54, 84]];
          i=0;
          while i < len(results):
           j=1;
           scores=[];
           while j < 4:
            scores.append(results[i][j]);
            j+=1;
           avg=float(sum(scores))/float(len(scores));
           print results[i][0]+": "+str(avg);
           i+=1;


          I'm not aware of any built in function in Python that calculates the average so, yes, I believe this is the way it should be done. Best case, this has a Big O of n^2, which is definitely not nice, but I've seen much worse algorithms.
          Last edited by computerfox; May 21 '15, 02:19 PM. Reason: More justification.

          Comment

          Working...