4

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.

3 Answers 3

3

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]]
Sign up to request clarification or add additional context in comments.

Comments

3

This should do :

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

split_index = 1

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

Comments

0

here without spliting, question is whats is the best for readability

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

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

6 Comments

I don't think it answers the question. Your sort depends on the second element of each list, right?
NO Eric, the sort key is relative in this case
Yes, but the question didn't mention it.
Let the OP decide. It matches the expectation for this exact example. But wouldn't work with ['a', 1, 8] as the first list.
Thank you for for trying Ari :) , but as Eric mentioned its for one particular case. But i wanted, is a generalized solution. Check Stephan and Eric's solutions both worked perfectly.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.