-1

I created a 3-d array for storing info for a bowling team. I've organized it in my head as a directory with teams in it and those teams have profiles in them and the profiles include player name, team number, and score.

I created a test list to use:

test = [
    [["John",1,153],["Lizzy",1,129],["Matt",1,178]],
    [["Jorge",2,156],["Brent",2,145],["Kyle",2,207]],
    [["Chuck",3,300]],
    [["Joey",4,230],["Stanley",4,60]]
]

I want to create a sorted list of all the profiles by their score, and also another list by name alphabetically. I could do this with for loops but it would look a lot nicer just using the sorted(). Is there a way to use the key parameter in the sorted() function to do this?

Mayank Patel
  • 3,868
  • 10
  • 36
  • 59
  • 1
    What's the expected output? – blhsing Apr 16 '19 at 01:08
  • You should use `numpy` if you want arrays. That's a nested `list`, and it's tedious to sort it the way you want. – gmds Apr 16 '19 at 01:18
  • @gmds what's tedious about `sorted`? – juanpa.arrivillaga Apr 16 '19 at 01:23
  • @juanpa.arrivillaga It seems tedious to sort all three levels in that way, each with their own key function. I could be wrong! – gmds Apr 16 '19 at 01:24
  • the expected output is to have all the profiles sorted by score, which i realized that it would essentially just break apart all the teams so what I did was write all the profiles into a new list and then sort that list using sorted(), with the key parameter as a function to select the 3rd index. here's what it looked like – Charlie Skinner Apr 16 '19 at 03:45
  • `def sort_score(directory): sorted_score = [] for team in directory: for profile in team: sorted_score.append(profile) sorted_score = sorted(sorted_score,key=takeScore,reverse=True) return sorted_score def takeScore(elem): return elem[2]` – Charlie Skinner Apr 16 '19 at 03:49
  • side question: how do I show code in a comment and have it format correctly? – Charlie Skinner Apr 16 '19 at 03:51
  • If you found an answer to your own question, post it as an answer. – Itamar Mushkin Apr 16 '19 at 04:52

2 Answers2

1

here's what I ended up doing

def sort_score(directory):
    sorted_score = []
    for team in directory:
        for profile in team:
            sorted_score.append(profile)
    sorted_score = sorted(sorted_score,key=takeScore,reverse=True)
    return sorted_score

def takeScore(elem):
    return elem[2]
0

You want to do two things: flatten the list and sort the result by a specific index.

from operator import itemgetter

test = [
    [["John",1,153],["Lizzy",1,129],["Matt",1,178]],
    [["Jorge",2,156],["Brent",2,145],["Kyle",2,207]],
    [["Chuck",3,300]],
    [["Joey",4,230],["Stanley",4,60]]
]

sorted_by_name = sorted([p for team in test for p in team], key=itemgetter(0))

sorted_by_score = sorted([p for team in test for p in team], key=itemgetter(2))
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73