1

I want to find 2D array's index and make it array. for example:

data_pre=[[1,1,1,0,0,0],[1,0,1,0,0,0],[1,0,0,0,1,0],[1,0,0,0,0,0]]

i wanna find index that have one and wanna make it like this

b=[[0,1,2],[0,2],[0,4],[0]]

Code:

result = []
for i in range(len(data_pre)):
    arr=data_pre[i]
    currentArrResult=[]
    for j in range(len(arr)):
        if arr[j]==1:
            currentArrResult.append(j)
            result.append(currentArrResult)

I tried like that but output is wrong.

[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 2], [0, 2], [0, 4], [0, 4], [0]]

I don't know which part is wrong...

  • 3
    You should reduce indentation of the last line so that it is at the same level as the innermost for loop. Right now, you are executing `result.append(currentArrResult)` for each `i` and `j`. I suppose that you mean to execute it once for each `i`. – hilberts_drinking_problem Jan 01 '22 at 06:49
  • 4
    By the way, you can express this more compactly as a list comprehension: `[[i for i, b in enumerate(row) if b] for row in data_pre]`. – hilberts_drinking_problem Jan 01 '22 at 06:50
  • This pattern: `for i in range(len(data_pre))` is unnecessarily roundabout. We can directly iterate over `data_pre` with `for arr in data_pre`. If the index is needed, we can use `enumerate`: `for i, arr in enumerate(data_pre)`. – Chris Jan 01 '22 at 06:55
  • Using `numpy`: [`np.where(np.any(x==15, axis=1)) for x in data_pre]`. See https://stackoverflow.com/questions/16094563/numpy-get-index-where-value-is-true – Larry the Llama Jan 01 '22 at 07:04

1 Answers1

0

you should not collect output inside the inner loop. that may get a result like this :

[[0],[0, 1],[0, 1, 2],
[0],[0, 2],
[0],[0, 4],
[0]]

you can check that by printing currentArrResult after append finish.
but you got different outcome because of data reference.

you should collect result after inner loop finish its work.
like:

result = []
for i in range(len(data_pre)):
    arr=data_pre[i]
    currentArrResult=[]
    for j in range(len(arr)):
        if arr[j]==1:
            currentArrResult.append(j)
           #print(currentArrResult)
    result.append(currentArrResult)
b m gevariya
  • 300
  • 1
  • 4
  • 12