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 !
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]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With