[英]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.