+

Python | Sort the list according to a different list order

Let`s discuss some ways to sort the list according to a different order of the list.

Method # 1: Using a comprehension list
List comprehension can be used to achieve this particular tasks. In this, we simply check that each element in list 2 matches the current tuple and add accordingly in a sorted manner.

# Python3 demo code
# sort by different list
# use comprehension list

  
# initializing the list of tuples

test_list = [( `a` , 1 ), ( `b` , 2 ), ( `c` , 3 ), ( `d` , 4 )]

 
# initialization sort order

sort_order = [ `d` , ` c` , ` a` , `b` ]

 
# print the original list

print ( "The original list is : " + str (test_list))

 
# print sort order list

print ( "The sort order list is:" + str (sort_order))

  
# using comprehension list
# sort by another list

res = [ tuple for x in sort_order for tuple in test_list if tuple [ 0 ] = = x ]

 
# print result

print ( "The sorted list is:" + str (res))

Exit:

 The original list is: [(`a`, 1), (` b`, 2), (`c`, 3), (` d`, 4)] The sort order list is: [`d`,` c`, `a`,` b`] The sorted list is: [(` d`, 4), (`c`, 3), (` a`, 1), (`b`, 2)] 

Method # 2: Usage sort () + lambda + index () [Works for Python2.]
Shorthand for doing this particular operation, the sort function can be used in conjunction with a keyed lambda expression to indicate the execution of the function for each pair of ko and the order of the list of another list is maintained using an index function.

# Python code for demo
# sort by another list
# using sort () + lambda + index ()

  
# initializing the list of tuples

test_list = [( `a` , 1 ), ( `b` , 2 ), ( `c` , 3 ), ( `d` , 4 )]

 
# initialize sort order

sort_order = [ `d` , `c` , ` a` , `b` ]

 
# print original list

print ( "The original list is:" + str (test_list))

  
# print the sort order list coding

print ( "The sort order list is: " + str (sort_order))

 
# using sort () + lambda + index ()
# sort by another list

test_list.sort (key = lambda (i, j): sort_order.index (i))

 
# print result

print ( "The sorted list is:" + str (test_list))

Exit:

< pre> The original list is: [(`a`, 1), (` b`, 2), (`c`, 3), (` d`, 4)] The sort order list is: [`d` , `c`,` a`, `b`] The sorted list is: [(` d`, 4), (`c`, 3), (` a`, 1), (`b`, 2) ]
Get Solution for free from DataCamp guru