Home > Back-end >  Filtering nested lists with python conditions
Filtering nested lists with python conditions

Time:11-08

how are you?

I have a distance matrix and need to perform a filter based on another list before applying some functions.

The matrix has 10 elements that represent machines and the distances between them, I need to filter this list by getting only the distances between some chosen machines.

matrix = [[0, 1, 3, 17, 24, 12, 18, 16, 17, 15],
          [1, 0, 2, 2, 5, 6, 13, 11, 12, 10],
          [3, 2, 0, 1, 6, 12, 18, 12, 17, 15],
          [17, 2, 1, 0, 3, 12, 17, 15, 16, 14],
          [24, 5, 6, 3, 0, 1, 24, 22, 23, 21],
          [12, 6, 12, 12, 1, 0, 12, 10, 11, 9],
          [18, 13, 18, 17, 24, 12, 0, 3, 4, 5],
          [16, 11, 12, 15, 22, 10, 3, 0, 1, 2],
          [17, 12, 17, 16, 23, 11, 4, 1, 0, 1],
          [15, 10, 15, 14, 21, 9, 5, 2, 1, 0]]

The list used for filtering, for example, is:

filter_list = [1, 2, 7, 10]

The idea is to use this list to filter the rows and the indices of the sublists to get the final matrix:

final_matrix = [[0, 1, 18, 15], 
                [1, 0, 13, 10], 
                [18, 13, 0, 5], 
                [15, 10, 5, 0]]

It is worth noting that the filter list elements vary. Can someone please help me?

That's what I tried:

final_matrix = []

for i in range(0, len(filter_list)):   
    for j in range(0,len(filter_list[i])):
        a = filter_list[i][j]
        final_matrix .append(matrix[a-1])
        print(final_matrix)

This is because the filter_list can have sublists. I get it:

final_matrix = [[0, 1, 3, 17, 24, 12, 18, 16, 17, 15], 
                [1, 0, 2, 2, 5, 6, 13, 11, 12, 10], 
                [18, 13, 18, 17, 24, 12, 0, 3, 4, 5], 
                [15, 10, 15, 14, 21, 9, 5, 2, 1, 0]]

I could not remove the spare elements.

CodePudding user response:

You forgot to filter by column ids. You can do this using nested list comprehensions.

final_matrix = [[matrix[row-1][col-1] for col in filter_list] for row in filter_list]

CodePudding user response:

final_matrix = []

for i in filter_list:
    to_append = []
    for j in filter_list:
        to_append.append(matrix[i-1][j-1])
    final_matrix.append(to_append)

or with list comprehension

final_matrix = [[matrix[i-1][j-1] for j in filter_list] for i in filter_list]
  • Related