+

Python | Sort a list of tuples in a specific order

Method # 1: Using list comprehension + filter () + lambda
The above three functions can be combined to accomplish a specific task in which list comprehension does iteration, the lambda function is used as a filter helper to sort by the second element of the tuple.

# Python3 demo code
# sort the list of tuples by seconds
# use comprehension list + filter () + lambda

 
# initialize the list of tuples

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

  
# initialize sort order

sort_order = [ 4 , 2 , 3 ]

 
# print original list

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

  
# print sort order list

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

 
# use comprehension list + filter () + lambda
# sort the list of tuples by seconds

res = [i for j in sort_order 

for i in filter ( lambda k: k [ 1 ] = = j, test_list)]

 
# print result

print ( "The list after appropriate sorting:" + str (res))

Exit:

 The original list is: [(`a`, 2), (` c`, 3), (`d`, 4)] The sort order list is: [4, 2, 3] The list after appropriate sorting: [(`d`, 4), (` a`, 2), (`c`, 3)]  

Method # 2: Using sorted () + index () + lambda
A sorted function can be used to sort according to the specified order. The index function specifies that the second element of the tuple should be counted and they are all concatenated using a lambda.

# Python3 demo code
# sort the list of tuples by seconds
# using sorted () + index () + lambda

 
# initialize the list of tuples

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

  
# initialize sort order

sort_order = [ 4 , 2 , 3 ]

 
# print original list

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

 
# print sort order list

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

 
# using sorted () + index () + lambda
# sort the list of tuples by seconds

res = list ( sorted (test_list, 

key = lambda i: sort_order.index (i [ 1 ])))

 
# print result

print ( "The list after appropriate sorting:" + str (res))

Exit:

 The original list is: [(`a`, 2) , (`c`, 3), (` d`, 4)] The sort order list is: [4, 2, 3] The list after appropriate sorting: [(`d`, 4), (` a`, 2), (`c`, 3)] 
Get Solution for free from DataCamp guru