Python | Relative sorted order in Matrix

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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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)]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.