Python | Sort list of tuples by specific ordering
Last Updated :
18 Apr, 2023
The normal sorting of tuples has been dealt previously. This article aims at sorting the given list of tuples by the second element, based on the order provided in some list.
Method #1 : Using list comprehension + filter() + lambda Above three functions can be combined to perform the particular task in which list comprehension performs the iteration, lambda function is used as helper function for filtering to sort according to second element of tuple.
Python3
test_list = [( 'a' , 2 ), ( 'c' , 3 ), ( 'd' , 4 )]
sort_order = [ 4 , 2 , 3 ]
print ( "The original list is : " + str (test_list))
print ( "The sort order list is : " + str (sort_order))
res = [i for j in sort_order
for i in filter ( lambda k: k[ 1 ] = = j, test_list)]
print ( "The list after appropriate sorting : " + str (res))
|
Output
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)]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using sorted() + index() + lambda The sorted function can be used to sort according to order specified. The index function specifies that second element of tuple has to be taken into considerations and all are joined with help of lambda.
Python3
test_list = [( 'a' , 2 ), ( 'c' , 3 ), ( 'd' , 4 )]
sort_order = [ 4 , 2 , 3 ]
print ( "The original list is : " + str (test_list))
print ( "The sort order list is : " + str (sort_order))
res = list ( sorted (test_list,
key = lambda i: sort_order.index(i[ 1 ])))
print ( "The list after appropriate sorting : " + str (res))
|
Output
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 #3 : Using for loop
Python3
test_list = [( 'a' , 2 ), ( 'c' , 3 ), ( 'd' , 4 )]
sort_order = [ 4 , 2 , 3 ]
print ( "The original list is : " + str (test_list))
print ( "The sort order list is : " + str (sort_order))
res = []
for i in sort_order:
for j in test_list:
if (j[ 1 ] = = i):
res.append(j)
print ( "The list after appropriate sorting : " + str (res))
|
Output
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 #4: Use a dictionary to map the sort order values to their corresponding tuples and then creating a sorted list of the mapped tuples.
Step-by-step approach:
- Create an empty dictionary to map the sort order values to their corresponding tuples.
- Iterate through the tuples in the test_list.
- For each tuple, add an entry to the dictionary with the second element of the tuple as the key and the tuple itself as the value.
- Create a list of the values in the dictionary (i.e., the tuples) using dict.values().
- Sort the list of tuples using sorted() and a lambda function that extracts the second element of the tuple.
- Return the sorted list.
Below is the implementation of the above approach:
Python3
test_list = [( 'a' , 2 ), ( 'c' , 3 ), ( 'd' , 4 )]
sort_order = [ 4 , 2 , 3 ]
print ( "The original list is : " + str (test_list))
print ( "The sort order list is : " + str (sort_order))
sort_dict = {}
for tup in test_list:
sort_dict[tup[ 1 ]] = tup
sorted_list = sorted (sort_dict.values(), key = lambda x: x[ 1 ])
print ( "The list after appropriate sorting : " + str (sorted_list))
|
Output
The original list is : [('a', 2), ('c', 3), ('d', 4)]
The sort order list is : [4, 2, 3]
The list after appropriate sorting : [('a', 2), ('c', 3), ('d', 4)]
Time complexity: O(n log n) due to sorting
Auxiliary space: O(n) for the dictionary
Method 5: Using the itemgetter() functionL
Steps:
- Import the operator module using the import statement.
- Initialize a list of tuples test_list with some values.
- Initialize a list sort_order with the desired sort order for the tuples.
- Define a key function key_func using the itemgetter() function from the operator module to extract the second element of each tuple.
- Use the sorted() function to sort the list of tuples test_list using the key function key_func. This returns a sorted list of tuples sorted_list.
- Create a new list of tuples res by iterating over the sorted list of tuples sorted_list and selecting only those tuples whose second element is in the sort order list sort_order.
- Print the result by converting the list of tuples to a string using the str() function.
Python3
import operator
test_list = [( 'a' , 2 ), ( 'c' , 3 ), ( 'd' , 4 )]
sort_order = [ 4 , 2 , 3 ]
key_func = operator.itemgetter( 1 )
sorted_list = sorted (test_list, key = key_func)
res = [t for t in sorted_list if t[ 1 ] in sort_order]
print ( "The list after appropriate sorting : " + str (res))
|
Output
The list after appropriate sorting : [('a', 2), ('c', 3), ('d', 4)]
Time complexity: O(n log n) (due to sorting)
Auxiliary space: O(n) (to store the sorted list)
Share your thoughts in the comments
Please Login to comment...