-1

I have this list called scores: [[['test', 1]], [['t', 4]], [['egrd', 8]], [['fds', 2]], [['dfs', 23]], [['wtr', 0]], [['reer', 1]]]

I am trying to order it by the number in each element so it becomes: [[['dfs', 23]], [['egrd', 8]], [['t', 4]], [['fds', 2]]. [['test', 1]], [['reer', 1]], [['wtr', 0]]]

I tried looping through the array and adding elements to a new a array based on their number element like this:

for x in range(0, 4): # loop through mulitple times to make sure it is ordered

    for i in range(0, len(scores) - 1):

        try:

            if scores[i][0][1] > scores[i + 1][0][1]: # compare each element against the one in front of it
                top_scores.append(scores[i]) # append to the new array

        except IndexError:
            pass

It returns this list: [[['egrd', 8]], [['dfs', 23]], [['egrd', 8]], [['dfs', 23]], [['egrd', 8]], [['dfs', 23]], [['egrd', 8]], [['dfs', 23]]]

Any help is much appreciated.

nat
  • 3
  • 1

2 Answers2

2

Use sorted with a custom key function

sorted(scores, key=lambda x: x[0][1], reverse=True)
tomjn
  • 5,100
  • 1
  • 9
  • 24
0

You can define a lambda function as a key in order to do this :

sorted(scores, key=lambda x: x[0][1], reverse=True)
Mohsen_Fatemi
  • 2,183
  • 2
  • 16
  • 25