Python – Reverse Row sort in Lists of List
Sometimes, while working with data, we can have a problem in which we need to perform the sorting of rows of the matrix in descending order. This kind of problem has its application in the web development and Data Science domain. Let’s discuss certain ways in which this task can be performed.
Method #1: Using loop + sort() + reverse This problem can be solved using a loop to loop over each row. The sort and reverse can be used to perform the reverse sort of rows.
Python3
# Python3 code to demonstrate # Reverse Row sort in Lists of List # using loop # initializing list test_list = [[ 4 , 1 , 6 ], [ 7 , 8 ], [ 4 , 10 , 8 ]] # printing original list print ( "The original list is : " + str (test_list)) # Reverse Row sort in Lists of List # using loop for ele in test_list: ele.sort(reverse = True ) # printing result print ( "The reverse sorted Matrix is : " + str (test_list)) |
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]
Time Complexity: O(n log n)
Auxiliary Space: O(1)
Method #2: Using list comprehension + sorted() This is yet another way in which this task can be performed. In this, we perform in a similar way, just pack the logic in one line using list comprehension to provide a compact alternative.
Python3
# Python3 code to demonstrate # Reverse Row sort in Lists of List # using list comprehension + sorted() # initializing list test_list = [[ 4 , 1 , 6 ], [ 7 , 8 ], [ 4 , 10 , 8 ]] # printing original list print ( "The original list is : " + str (test_list)) # Reverse Row sort in Lists of List # using list comprehension + sorted() res = [ sorted (sub, reverse = True ) for sub in test_list] # printing result print ( "The reverse sorted Matrix is : " + str (res)) |
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]
Time Complexity: O(n log n)
Auxiliary Space: O(n)
Method#3: Using map() + sorted This is one way to solve this problem. In this, we update the existing list with the help of map function which sorts the internal list in reverse order using the sorted function.
Python3
# Python3 code to demonstrate # Reverse Row sort in Lists of List # using map + sorted() # initializing list test_list = [[ 4 , 1 , 6 ], [ 7 , 8 ], [ 4 , 10 , 8 ]] # printing original list print ( "The original list is : " + str (test_list)) # Reverse Row sort in Lists of List # using map + sorted() res = list ( map ( lambda x: sorted (x, reverse = True ), test_list)) # printing result print ( "The reverse sorted Matrix is : " + str (res)) |
The original list is : [[4, 1, 6], [7, 8], [4, 10, 8]] The reverse sorted Matrix is : [[6, 4, 1], [8, 7], [10, 8, 4]]
Time Complexity: O(n log n)
Auxiliary Space: O(n)
Please Login to comment...