简体   繁体   English

在二维数组的情况下查找索引

[英]Find index in a case of 2D array

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.我试过这样,但 output 是错误的。

[[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...不知道哪一部分错了...

you should not collect output inside the inner loop.您不应该在内循环内收集 output 。 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.您可以在currentArrResult完成后打印 currentArrResult 来检查。
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM