1

I have a tuple which currently looks like the following:

[['Hussain', 7, 8, 0], ['Max', 3, 4, 3], ['Alexandra', 10, 9, 8]]

I want to be able to sort this tuple so that it prints out the tuple in order from highest to lowest averages. This is what I expect as the outcome:

['Alexandra', 9],['Hussain', 5],['Max', 3.3333333333]

I would appreciate any help given.

TIA

Hussain
  • 51
  • 5

2 Answers2

3
from statistics import mean
from operator import itemgetter
l = [['Hussain', 7, 8, 0], ['Max', 3, 4, 3], ['Alexandra', 10, 9, 8]]

print(sorted(([ele[0],mean(ele[1:])] for ele in l),key=itemgetter(1),reverse=True))

[['Alexandra', 9.0], ['Hussain', 5.0], ['Max', 3.3333333333333335]] 

If you are not using python >= 3.4 you can just do the average calculation manually.

print(sorted(([ele[0],sum((ele[1:])) /  len(l) - 1] for ele in l),key=itemgetter(1),reverse=True))

ele[0],mean(ele[1:]) takes the name and the remaining elements which are the scores, we then sort using itemgetter(1) which is the score/second element as the key and setting reverse=True to go from high to low.

I would also use itertools.islice to get the slice avoiding building new lists with normal slicing:

from itertools import islice
print(sorted(([ele[0],mean(islice(ele,1,None))] for ele in l),key=itemgetter(1),reverse=True))

Or without using mean:

from itertools import islice
print(sorted(([ele[0],sum(islice(ele,1,None)) / len(l) - 1] for ele in l),key=itemgetter(1),reverse=True))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1
s = [['Hussain', 7, 8, 0], ['Max', 3, 4, 3], ['Alexandra', 10, 9, 8]]
result = sorted([[e[0], sum(e[1:])/len(e[1:])] for e in s], key=lambda x: x[1], reverse=True)
Jaakko
  • 584
  • 6
  • 13
  • Sorted needs an iterable. I'm using list comprehension to give sorted the first parameter: [[e[0], sum(e[1:])/len(e[1:])] for e in s] = > [['Hussain', 5.0], ['Max', 3.3333333333333335], ['Alexandra', 9.0]] – Jaakko Apr 10 '15 at 22:48
  • I used timeit to see how our functions compare. With number=10000, your answer gets: 1.5141523819997929 Mine gets: 0.08450542999980826 – Jaakko Apr 10 '15 at 22:58
  • Your first answer: from statistics import mean from operator import itemgetter sorted(([ele[0],mean(ele[1:])] for ele in l),key=itemgetter(1),reverse=True) Maybe the imports slow it down. Anyway, what's the problem with my answer? It's fast, one line, clear and list comprehensions are great. – Jaakko Apr 10 '15 at 23:16
  • Dude, why did you delete your comments? – Jaakko Apr 10 '15 at 23:22