Syed Syed - 16 days ago 6
Python Question

Nested list and sorting in python

I don't know if it is possible or not. I am trying to find a way of sorting a nested list on the following condition


  1. i want to sort form 1 point to another (NOT the whole list only part of it)

  2. the sorting should be done on the basis of 3rd element of the sublists



an Idea of what i want:

PAE=[['a',0,8],
['b',2,1],
['c',4,3],
['d',7,2],
['e',8,4]]

#PAE[1:4].sort(key=itemgetter(2)) (something like this)
or
#sorted(PAE[1:4],key=itemgetter(2)) (something like this)
` # ^ i know both are wrong but just for an idea
`
#output should be like this
['a', 0, 8]
['b', 2, 1]
['d', 7, 2]
['c', 4, 3]
['e', 8, 4]


I am new to python, but i tried my level best to find a solution but failed.

Answer

Sort the slice and write it back:

>>> PAE[1:4] = sorted(PAE[1:4], key=itemgetter(2))
>>> PAE
[['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]]