Problem: Given a matrix, extract all the rows that all have elements with a particular data type.
isinstance()
+ all()
+ list comprehensionIn 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 = intres = [row for row in test_list if all(isinstance(ele, data_type) for ele in row)]print("Filtered Rows : " + str(res))
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 = intres = list(filter(lambda row: all(isinstance(ele, data_type)for ele in row), test_list))print("Filtered Rows : " + str(res))