Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

extract
python3
data types
community creator

How to extract particular data type rows

Bhanu

Problem: Given a matrix, extract all the rows that all have elements with a particular data type.

Method 1 : Using isinstance() + all() + list comprehension

In this method, we use isinstance() and all() to check for all the elements of a particular data type.

test_list = [[4, 5, "Hello"], [2, 6, 7], ["g", "f", "g"], [9, 10, 11]] 
 
print("The original list is : " + str(test_list)) 
   
data_type = int
 
res = [row for row in test_list if all( 
    isinstance(ele, data_type) for ele in row)] 
  
print("Filtered Rows : " + str(res)) 

Method 2 : Using filter() + lambda + isinstance()

In this method, we will perform the task of filtering using filter() and lambda isinstance().

test_list = [[4, 5, "Hello"], [2, 6, 7], ["g", "f", "g"], [9, 10, 11]] 
  
print("The original list is : " + str(test_list)) 
  
data_type = int
 
res = list(filter(lambda row: all(isinstance(ele, data_type) 
for ele in row), test_list)) 

print("Filtered Rows : " + str(res))

RELATED TAGS

extract
python3
data types
community creator
RELATED COURSES

View all Courses

Keep Exploring