Add elements to a list of lists (Node neighbors)

Viewed 45
import numpy as np
E = np.array([[1, 2, 4],
              [2, 5, 4],
              [2, 3, 5],
              [3, 6, 5],
              [4, 5, 7],
              [5, 8, 7],
              [5, 6, 8],
              [6, 9, 8]])
Nn = np.max(E)
print("maximum node number: \n", Nn)
n_row, n_column = E.shape
print("\n", n_row, n_column)
n_list = [[] for x in range(Nn)]
print("\n initialize n vector\n", n_list)
k = 1
while k <= Nn:
    print(k)
    for i in range(n_row):
        for j in range(n_column):
            if E[i, j] == k:
                n_list[i].append(E[i, :])
    k = k + 1
print("\n n vector\n", n_list)

I'm new to programming. I have a matrix that shows how 9 nodes are connected. If nodes appear in the same row then they are connected. I created a list of lists (9 rows) so that, for each node from 1 to 9, I can add the entire row of matrix to the specific row of list. For example, for node 1, I want to add the entire first row of matrix to the first row of list. And for the node 2, I want to add row 1, 2, 3 of the matrix to the second row of list. How do I fix this code to do that?

1 Answers

Using NumPy modules will make the code easier to do (IDK if pandas groupby could do it faster if it could, but I show it by NumPy). It can be done by looping and find rows of the array that contain the corresponding value. This can be done by creating a mask array that shows which row must be added. When the corresponding rows are determined in each loop, they can be appended to a list as arrays or as lists:

counter_ = np.arange(E.min(), E.max() + 1)
# [1 2 3 4 5 6 7 8 9]

L = []
for i in counter_:
    mask = (E == i).any(1)
    L.append(E[mask])

L will be a list of 2d arrays (each array contain its corresponding rows). These 2d arrays can be replaced by lists if needed.

In your code, you don't need to create empty list of lists at first. It must be just a list (L) that will be filled (appended) by other lists in each loop. Lists (temp_L) that contain rows will be created in loops and appended to that main list at the end of each loop. Note that there is no need to continue loops on columns of a row if we found the corresponding value in that row on one of its columns e.g., if we are looping on the row 2, if we found 2 in 1th column, so we break that avoid extra looping from 2th column to the end in that row. So your code must be modified to:

Nn = np.max(E)
print("maximum node number: \n", Nn)
n_row, n_column = E.shape
print("\n", n_row, n_column)
n_list = []
print("\n initialize n vector\n", n_list)
k = 1
while k <= Nn:
    print(k)
    temp_l = []
    for i in range(n_row):
        for j in range(n_column):
            if E[i, j] == k:
                temp_l.append(E[i, :])
                break
    n_list.append(temp_l)
    k = k + 1
print("\n n vector\n", n_list)
Related