Home > Software engineering >  Finding index in nested list of arrays while looping in Python
Finding index in nested list of arrays while looping in Python

Time:08-04

I tried to find the index of nested array elements that are inside of list while the If condition is met (the value in the array should be greater than 0), and the desired output should be new_nodes_idx = [0, 0, 0, 0, 1, 1, 1, 1]. Instead of this desired output, i got one that is new_nodes_idx = [0, 0, 0, 0, 0, 0, 0, 0]. Here is the code that i used:

import numpy as np

NoF = 2

a1 = np.array([40, 0])
a2 = np.array([80, 0])
a3 = np.array([120, 0])
a4 = np.array([160, 40])
a5 = np.array([0, 80])
a6 = np.array([0, 120])
a7 =  np.array([0, 160])

ml_a = [a1, a2, a3, a4, a5, a6, a7]    
new_nodes_idx =[]
    for i in range(int(len(ml_a))):
        for k in range(0, int(len(a1))):
            for idx, x in enumerate(ml_a[i]):
                if ml_a[i][k] > 0:
                    new_nodes_idx.append(idx)
                    break

Any provided help is appreciated.

CodePudding user response:

There is one loop too much in your approach. for k in ... already loops through each of the arrays. In the next line you want to do that again with enumerate.

I cleaned your code a bit. You can access the elements of the loop directly in python with for arr in list, no need for for i in range(len(list)).

ml_a = [a1, a2, a3, a4, a5, a6, a7]    
new_nodes_idx =[]
for arr in ml_a: # arr is a1, a2 ...,a7
    for idx, val in enumerate(arr): 
    # example for a1: 1. iteration: idx=0, val=40
    #                 2. iteration: idx=1, val=0
        if val > 0:
            new_nodes_idx.append(idx)
            break
                
print(new_nodes_idx)

Output:

[0, 0, 0, 0, 1, 1, 1]
  • Related