5

I am looking for a way to sort my array of array which has a complex structure :

L=[[
[[1,1,1,1,1,1,1],1,56],
[[6,6,6,6,6,6,6],1,3],
[[3,3,3,3,3,3,3],1,54]],
[[[2,2,2,2,2,2,2],2,42],
[[5,5,5,5,5,5,5],2,6]]]

I woul'd like to sort it by the last elements meaning (56, 3, 54 and 42, 6). What I want to get it is that :

L=[[
[[6,6,6,6,6,6,6],1,3],
[[3,3,3,3,3,3,3],1,54],
[[1,1,1,1,1,1,1],1,56]],
[[[5,5,5,5,5,5,5],2,6],
[[2,2,2,2,2,2,2],2,42]]]

I have already tried : L.sort(key=lambda x: x[0][0][2]) but it doesn't work...

I have seen those advices but I haven't succeeded in making it work :

How to sort a list of lists by a specific index of the inner list?

Any help would be appreciated ! Thanks in advance !

0

1 Answer 1

4

You can use itemgetter to sort multiple index.
In this case, sort index 1 and then index 2 on L[i]

import operator
for i in range(len(L)):
    L[i] = sorted(L[i], key=operator.itemgetter(1, 2))

or simpler:

import operator
    for s in L:
        s.sort(key=operator.itemgetter(1, 2))

thanks to @georg

output:

[[[[6, 6, 6, 6, 6, 6, 6], 1, 3],
  [[3, 3, 3, 3, 3, 3, 3], 1, 54],
  [[1, 1, 1, 1, 1, 1, 1], 1, 56]],
 [[[5, 5, 5, 5, 5, 5, 5], 2, 6], 
  [[2, 2, 2, 2, 2, 2, 2], 2, 42]]]
Sign up to request clarification or add additional context in comments.

5 Comments

You can simplify this: for s in L: s.sort(...). No need for indexes - lists are references!
No, s = sorted(s) won't work! s.sort() is crucial.
I'm confused. Why s=sorted(s) won't work, while my original answer L[i] = sorted(L[i]) works?
Because L[i]=... modifies the value of L itself, while s=... just assigns a new value to s.
Thanks @georg, I modified my answer again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.