繁体   English   中英

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

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

我想找到二维数组的索引并将其设为数组。 例如:

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]]

我想找到有一个的索引,并想让它像这样

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

代码:

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)

我试过这样,但 output 是错误的。

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

不知道哪一部分错了...

您不应该在内循环内收集 output 。 可能会得到这样的结果:

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

您可以在currentArrResult完成后打印 currentArrResult 来检查。
但是由于数据参考,您得到了不同的结果。

您应该在内循环完成其工作后收集结果。
喜欢:

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