Syed Syed - 1 year ago 101
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[1:4].sort(key=itemgetter(2)) (something like this)
#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 Source

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]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download