By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,813 Members | 2,269 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,813 IT Pros & Developers. It's quick & easy.

working out the average within a nested list

P: 7
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
May 20 '15 #1
Share this Question
Share on Google+
4 Replies


Expert 100+
P: 616
Calculate it for each item in the list and create a 2nd list with the average as the first sub-item.
Expand|Select|Wrap|Line Numbers
  1. test_list=[[20, "Ben", 15, 18,25], [50, "George", 25, 35, 85], [19, "Evie", 2, 54, 84]]
  2. test_list.sort
  3. print test_list 
May 20 '15 #2

computerfox
100+
P: 278
Expand|Select|Wrap|Line Numbers
  1. #!/bin/python
  2. results = [["Ben", 15, 18,25], ["George", 25, 35, 85], ["Evie", 2, 54, 84]];
  3. i=0;
  4. while i < len(results):
  5.  j=1;
  6.  scores=[];
  7.  while j < 4:
  8.   scores.append(results[i][j]);
  9.   j+=1;
  10.  scores.sort();
  11.  print results[i][0]+": "+str(scores[2])+","+str(scores[1])+","+str(scores[0]);
  12.  i+=1;
  13.  
http://safe.abelgancsos.com/codepost...ect.php?id=383
May 21 '15 #3

P: 7
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?
May 21 '15 #4

computerfox
100+
P: 278
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:
Expand|Select|Wrap|Line Numbers
  1. #!/bin/python
  2. results = [["Ben", 15, 18,25], ["George", 25, 35, 85], ["Evie", 2, 54, 84]];
  3. i=0;
  4. while i < len(results):
  5.  j=1;
  6.  scores=[];
  7.  while j < 4:
  8.   scores.append(results[i][j]);
  9.   j+=1;
  10.  avg=float(sum(scores))/float(len(scores));
  11.  print results[i][0]+": "+str(avg);
  12.  i+=1;
  13.  
http://safe.abelgancsos.com/codepost...ect.php?id=384

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.
May 21 '15 #5

Post your reply

Sign in to post your reply or Sign up for a free account.