Python | Relative sorted order in Matrix
Last Updated :
13 Apr, 2023
Sometimes, while working with Python Matrix, we can have data arranged randomly and we can have a requirement in which we need to get the element position in sorted order of Matrix. Let's discuss a certain way in which this task can be performed. Method : Using list comprehension + enumerate() + sort() + lambda The solution to problem can be achieved using the combination of above functions. In these, we need to first arrange element for index value tuple creation using enumerate() and list comprehension. Then, we employ sort function to perform custom sort using lambda function.
Code :
Python3
# Python3 code to demonstrate working of
# Relative sorted order in Matrix
# using list comprehension + enumerate() + sort() + lambda
# initialize list
test_list = [[1, 3, 1], [4, 6], [7, 8, 10]]
# printing original list
print("The original list is : " + str(test_list))
# Relative sorted order in Matrix
# using list comprehension + enumerate() + sort() + lambda
res = [(i, j) for i, x in enumerate(test_list) for
j, _ in enumerate(x)]
res.sort(key = lambda f: test_list[f[0]][f[1]])
# printing result
print("Sorted order of Matrix elements : " + str(res))
Output : The original list is : [[1, 3, 1], [4, 6], [7, 8, 10]]
Sorted order of Matrix elements : [(0, 0), (0, 2), (0, 1), (1, 0),
(1, 1), (2, 0), (2, 1), (2, 2)]
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method #2: Using numpy and argsort
Step by step Algorithm:
- Initialize a 2D list matrix with some values and a list relative_order containing the desired order of the elements.
- Create a flattened numpy array flat_array from the matrix.
- Use a list comprehension to get the indices in relative_order for each element in flat_array, if it exists in relative_order, otherwise use the
- length of relative_order as the index.
- Use numpy.argsort() to get the indices that would sort the array in ascending order.
- Use numpy.unravel_index() to reshape the sorted indices into the shape of the original matrix.
- Print the result.
Python3
import numpy as np
# define the original matrix and the relative order list
matrix = [[1, 3, 1], [4, 6], [7, 8, 10]]
relative_order = [1, 3, 5, 7, 2, 4, 6, 8, 9, 10]
# create a flattened numpy array from the matrix
flat_array = np.array([elem for row in matrix for elem in row])
# get the indices that would sort the array in ascending order
sorted_indices = np.argsort([np.where(np.array(relative_order) == elem)[0][0] if elem in relative_order else len(relative_order) for elem in flat_array])
# reshape the sorted indices into the shape of the original matrix
sorted_matrix = np.unravel_index(sorted_indices, np.shape(matrix))
# print the result
print("The original matrix is:", matrix)
print("Sorted order of Matrix elements:", list(zip(sorted_matrix[0], sorted_matrix[1])))
OutputThe original list is :[[1, 3, 1], [4, 6], [7, 8, 10]]
Sorted order of Matrix elements : [(0, 0), (0, 2), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2)]
Time Complexity: O(nlogn), where n is the number of elements in the matrix, due to the np.argsort() function used.
Space Complexity: O(n), as we are creating a flattened numpy array of the original matrix and also storing the sorted indices.
Method #3: Using itertools.product() and list comprehension
- Import the itertools module.
- Initialize the matrix as a list of lists.
- Print the original matrix.
- Use itertools.product() to generate pairs of row and column indices for each element in the matrix.
- Use a list comprehension to filter out invalid indices.
- Sort the resulting list of tuples based on the element values in the matrix.
- Print the sorted list of tuples.
Python3
import itertools
# initialize list
test_list = [[1, 3, 1], [4, 6], [7, 8, 10]]
# printing original list
print("The original list is : " + str(test_list))
# Relative sorted order in Matrix
# using itertools.product() and list comprehension
res = [(i, j) for i, j in itertools.product(range(len(test_list)), range(max(map(len, test_list)))) if j < len(test_list[i])]
res.sort(key = lambda f: test_list[f[0]][f[1]])
# printing result
print("Sorted order of Matrix elements : " + str(res))
OutputThe original list is : [[1, 3, 1], [4, 6], [7, 8, 10]]
Sorted order of Matrix elements : [(0, 0), (0, 2), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2)]
Time complexity: O(n*log(n)), where n is the number of rows in the matrix
Space complexity: O(n), where n is the number of rows in the matrix.
Similar Reads
How to reverse column order in a matrix with Python? In this article, we will see how to reverse the column order of a matrix in Python. Examples: Input: arr = [[10,20,30], [40,50,60], [70,80,90]] Output: 30 20 10 60 50 40 90 80 70 Input: arr = [[15,30], [45,60], [75,90], [105,120]] Output: 30 15 60 45 90 75 120 105 Matrices are created in python by u
2 min read
Sort a Pandas Series in Python Series is a one-dimensional labeled array capable of holding data of the type integer, string, float, python objects, etc. The axis labels are collectively called index. Now, Let's see a program to sort a Pandas Series. For sorting a pandas series the Series.sort_values() method is used. Syntax: Se
3 min read
Python | Numpy matrix.sort() With the help of matrix.sort() method, we are able to sort the values in a matrix by using the same method. Syntax : matrix.sort() Return : Return a sorted matrix Example #1 : In this example we are able to sort the elements in the matrix by using matrix.sort() method. Python3 1=1 # import the impor
1 min read
numpy.searchsorted() in Python numpy.searchsorted() function is used to find the indices into a sorted array arr such that, if elements are inserted before the indices, the order of arr would be still preserved. Here, binary search is used to find the required insertion indices. Syntax : numpy.searchsorted(arr, num, side='left',
3 min read
Python | Pandas Series.sort_index() Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.sort_index() function is used
2 min read