Python program to remove row with custom list element

Python program to remove row with custom list element

In this tutorial, we will learn how to remove rows from a matrix if the row contains an element from a custom list.

Scenario: Given a matrix like:

matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] 

And a custom list of:

custom_list = [5, 7] 

After removing rows that contain elements from the custom_list, the resulting matrix should be:

[ [1, 2, 3] ] 

Steps:

  1. Define a function to check if a row contains any element from the custom list.
  2. Use a list comprehension to filter out rows based on the check from step 1.

Python Code:

def contains_custom_element(row, custom_list): """ Checks if the given row contains any element from the custom list. :param row: List of elements. :param custom_list: Custom list of elements. :return: True if row contains any element from custom list, False otherwise. """ return any(element in custom_list for element in row) def remove_rows_with_custom_elements(matrix, custom_list): """ Removes rows from the matrix that contain elements from the custom list. :param matrix: List of lists representing the matrix. :param custom_list: Custom list of elements. :return: Matrix with rows containing elements from custom list removed. """ return [row for row in matrix if not contains_custom_element(row, custom_list)] # Example usage: matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] custom_list = [5, 7] filtered_matrix = remove_rows_with_custom_elements(matrix, custom_list) for row in filtered_matrix: print(row) 

Explanation:

  • We first define a helper function contains_custom_element that takes a row and a custom list as inputs. The function checks if the row contains any element from the custom list using the any() function along with a generator expression.
  • Next, we define the function remove_rows_with_custom_elements. Using a list comprehension, we filter out rows that contain any element from the custom list.
  • In the example usage, we call the remove_rows_with_custom_elements function on our matrix with the given custom list and print the resulting rows.

This approach provides a clear and efficient way to filter out rows based on a custom list of elements. The code can be adapted to handle variations or additional requirements if needed.


More Tags

hashmap wiremock strikethrough ios8 fixed spring-rabbit fiddler stripe-payments child-process reverse-proxy

More Programming Guides

Other Guides

More Programming Examples