我想找到二維陣列的索引并將其設為陣列。例如:
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)
我這樣試過,但輸出是錯誤的。
[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 2], [0, 2], [0, 4], [0, 4], [0]]
不知道是哪部分錯了...
uj5u.com熱心網友回復:
您不應該在內回圈內收集輸出。可能會得到這樣的結果:
[[0],[0, 1],[0, 1, 2],
[0],[0, 2],
[0],[0, 4],
[0]]
您可以通過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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/400866.html
