Tom Smith
Tom Smith

Reputation: 371

python sort itemgetter equivalent for N-dimensional nested lists

To sort a nested 2D list (list2D) by the nth element of the second dimension in python 2.7 I can use

import operator
sorted(list2D, key=operator.itemgetter(n))

How can I sort the second dimension of a 3D list (list3D) based on the nth elements of the second and third dimensions?

This would sort list3D below, currently in order 4,7,2.

list3D = [[[5,4,5,7],
           [0,1,1,0]],
          [[2,7,5,7],
           [1,0,0,1]],
          [[1,2,5,7],
           [1,1,1,0]]]

into sort3D below where it sorted by indices [0][1] of the second and third dimensions as 2,4,7

sort3D = [[[1,2,5,7],
           [1,1,1,0]],
          [[5,4,5,7],
           [0,1,1,0]],
          [[2,7,5,7],
           [1,0,0,1]]]

Upvotes: 3

Views: 1881

Answers (1)

Cyrbil
Cyrbil

Reputation: 6478

sorted() can accept a lambda that will be given an element and should return something sortable (here your value) to sort the results:

>>> list3D = [[[5,4,5,7],
               [0,1,1,0]],
              [[2,7,5,7],
               [1,0,0,1]],
              [[1,2,5,7],
               [1,1,1,0]]]
>>> sorted(list3D, key=lambda x: x[0][1])
[[[1, 2, 5, 7], [1, 1, 1, 0]], [[5, 4, 5, 7], [0, 1, 1, 0]], [[2, 7, 5, 7], [1, 0, 0, 1]]]

The doc have a great appendix about using key=

Upvotes: 3

Related Questions