Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a complex structure of array of array

Tags:

python

arrays

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 !

like image 378
Pauline1006 Avatar asked Sep 29 '22 11:09

Pauline1006


1 Answers

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]]]
like image 68
Aaron Avatar answered Oct 05 '22 07:10

Aaron