Sort list of tuples by specific ordering – Python
Sorting a list of tuples by a specific order requires us to define a custom logic for the sorting process.
For example, given a list of tuples like [(1, 'Python'), (2, 'with'), (3, 'GFG')]
, we might want to sort it based on a predefined order of the second element such as ['with', 'GFG', 'Python']
. Let’s explore different methods to achieve this in Python.
Using sorted() with a custom key
This method uses the sorted() function, which allows us to pass a custom key function for sorting.
# Input list of tuples
a = [(1, 'Python'), (2, 'with'), (3, 'GFG')]
# Define the specific order
order = ['with', 'Python', 'GFG']
# Sort the list of tuples based on the specific order
res = sorted(a, key=lambda x: order.index(x[1]))
print(res)
Output
[(2, 'with'), (1, 'Python'), (3, 'GFG')]
Explanation:
- We define the order of the elements in the list
order
. - key function uses the
index()
method to find the position of the second element of each tuple in the predefined order list. - sorted() function arranges the tuples based on these positions.
Let’s explore some more ways and see how we can sort list of tuples by specific ordering.
Table of Content
Using a dictionary for mapping
This method introduces a dictionary to map each element in the predefined order to its position. It improves efficiency compared to using index() repeatedly.
# Input list of tuples
a = [(1, 'Python'), (2, 'with'), (3, 'GFG')]
# Define the specific order
order = ['with', 'GFG', 'Python']
# Create a mapping of elements to their positions
order_map = {value: index for index, value in enumerate(order)}
# Sort the list of tuples using the mapping
res = sorted(a, key=lambda x: order_map[x[1]])
print(res)
Output
[(2, 'with'), (3, 'GFG'), (1, 'Python')]
Explanation:
- We create a dictionary
order_map
to store the position of each element in the predefined order list. - The key function directly retrieves the position of the second element from the dictionary instead of repeatedly calling index().
Using for loop
This method involves manually sorting the list of tuples using a loop and comparing each element with the predefined order list.
# Input list of tuples
a = [(1, 'Python'), (2, 'with'), (3, 'GFG')]
# Define the specific order
order = ['with', 'GFG', 'Python']
# Initialize an empty list to store the sorted tuples
res = []
# Iterate through the predefined order
for item in order:
for i in a:
if i[1] == item:
res.append(i)
print(res)
Output
[(2, 'with'), (3, 'GFG'), (1, 'Python')]
Explanation:
- We manually iterate through the predefined order and check for matching elements in the original list of tuples.
- Matching tuples are added to the result list in the correct order.
- While simple, this method is the least efficient due to the nested loops, making it unsuitable for large datasets.