Sort complex array array structure

I am looking for a way to sort an array of an array that 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 wanted to sort it by the last element values ​​(56, 3, 54 and 42, 6). What I want to get 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 already tried: L.sort(key=lambda x: x[0][0][2]) but it does not work ...

I saw these tips, but I was not able to get it to work:

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

Any help would be appreciated! Thanks in advance!

+5
source share
1 answer

You can use itemgetter to sort multiple indexes.
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 @georg

exit:

 [[[[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]]] 
+4
source

Source: https://habr.com/ru/post/1215994/


All Articles