Wednesday, November 27, 2024
Google search engine
HomeLanguagesPython | Sort list of tuples by specific ordering

Python | Sort list of tuples by specific ordering

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




# Python3 code to demonstrate
# sort list of tuples according to second
# using list comprehension + filter() + lambda
 
# initializing list of tuples
test_list = [('a', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = [4, 2, 3]
 
# printing the original list
print("The original list is : " + str(test_list))
 
# printing sort order list
print("The sort order list is : " + str(sort_order))
 
# using list comprehension + filter() + lambda
# sort list of tuples according to second
res = [i for j in sort_order
       for i in filter(lambda k: k[1] == j, test_list)]
 
# printing result
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




# Python3 code to demonstrate
# sort list of tuples according to second
# using sorted() + index() + lambda
 
# initializing list of tuples
test_list = [('a', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = [4, 2, 3]
 
# printing the original list
print("The original list is : " + str(test_list))
 
# printing sort order list
print("The sort order list is : " + str(sort_order))
 
# using sorted() + index() + lambda
# sort list of tuples according to second
res = list(sorted(test_list,
                  key=lambda i: sort_order.index(i[1])))
 
# printing result
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




# Python3 code to demonstrate
# sort list of tuples according to second
 
# initializing list of tuples
test_list = [('a', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = [4, 2, 3]
 
# printing the original list
print("The original list is : " + str(test_list))
 
# printing sort order 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)
 
# printing result
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




# Python3 code to demonstrate
# sort list of tuples according to second
 
# initializing list of tuples
test_list = [('a', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = [4, 2, 3]
 
# printing the original list
print("The original list is : " + str(test_list))
 
# printing sort order list
print("The sort order list is : " + str(sort_order))
 
# mapping sort order values to tuples
sort_dict = {}
for tup in test_list:
    sort_dict[tup[1]] = tup
 
# creating sorted list of tuples
sorted_list = sorted(sort_dict.values(), key=lambda x: x[1])
 
# printing result
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:

  1. Import the operator module using the import statement.
  2. Initialize a list of tuples test_list with some values.
  3. Initialize a list sort_order with the desired sort order for the tuples.
  4. Define a key function key_func using the itemgetter() function from the operator module to extract the second element of each tuple.
  5. 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.
  6. 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.
  7. Print the result by converting the list of tuples to a string using the str() function.

Python3




# importing the operator module
import operator
 
# initializing list of tuples
test_list = [('a', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = [4, 2, 3]
 
# define a key function using the
# itemgetter() function to extract
# the second element of each tuple
key_func = operator.itemgetter(1)
 
# sort the list of tuples using the
# sorted() function with the key
# function defined above
sorted_list = sorted(test_list, key=key_func)
 
# create a list of tuples in the
# same order as the sort order list
res = [t for t in sorted_list if t[1] in sort_order]
 
# printing result
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)

RELATED ARTICLES

Most Popular

Recent Comments