Python Program that filters out non-empty rows of a matrix
Given Matrix, the following article shows how to filter all the Non-Empty rows of a matrix. In simpler terms, the codes provided below return a matrix after removing empty rows from it.
Input : test_list = [[4, 5, 6, 7], [], [], [9, 8, 1], []] Output : [[4, 5, 6, 7], [9, 8, 1]] Explanation : All empty rows are removed. Input : test_list = [[4, 5, 6, 7], [], [9, 8, 1], []] Output : [[4, 5, 6, 7], [9, 8, 1]] Explanation : All empty rows are removed.
Method 1: Using list comprehension and len()
In this we check each row for its length, if its length is greater than 0 then that row is added to result.
Python3
# initializing list test_list = [[ 4 , 5 , 6 , 7 ], [], [], [ 9 , 8 , 1 ], []] # printing original lists print ( "The original list is : " + str (test_list)) # checking for row lengths using len() res = [row for row in test_list if len (row) > 0 ] # printing result print ( "Filtered Matrix " + str (res)) |
Output
The original list is : [[4, 5, 6, 7], [], [], [9, 8, 1], []] Filtered Matrix [[4, 5, 6, 7], [9, 8, 1]]
Method 2 : Using filter(), lambda and len()
In this, we filter rows w.r.t lengths using filter() and lambda function. The len() is used to get the length.
Python3
# initializing list test_list = [[ 4 , 5 , 6 , 7 ], [], [], [ 9 , 8 , 1 ], []] # printing original lists print ( "The original list is : " + str (test_list)) # checking for row lengths using len() # filtering using filter() + lambda res = list ( filter ( lambda row: len (row) > 0 , test_list)) # printing result print ( "Filtered Matrix " + str (res)) |
Output:
The original list is : [[4, 5, 6, 7], [], [], [9, 8, 1], []]
Filtered Matrix [[4, 5, 6, 7], [9, 8, 1]]
Method 3 : Using find() method
Python3
#Filter non empty rows # initializing list test_list = [[ 4 , 5 , 6 , 7 ], [], [], [ 9 , 8 , 1 ], []] # printing original lists print ( "The original list is : " + str (test_list)) res = [] for i in test_list: if str (i).find( "[]" ) = = - 1 : res.append(i) # printing result print ( "Filtered Matrix " + str (res)) |
Output
The original list is : [[4, 5, 6, 7], [], [], [9, 8, 1], []] Filtered Matrix [[4, 5, 6, 7], [9, 8, 1]]
Method 4 : Using remove() method
Python3
#Python Program that filters out non-empty rows of a matrix # initializing list test_list = [[ 4 , 5 , 6 , 7 ], [], [], [ 9 , 8 , 1 ], []] # printing original lists print ( "The original list is : " + str (test_list)) while ([] in test_list): test_list.remove([]) # printing result print ( "Filtered Matrix " + str (test_list)) |
Output
The original list is : [[4, 5, 6, 7], [], [], [9, 8, 1], []] Filtered Matrix [[4, 5, 6, 7], [9, 8, 1]]
Please Login to comment...