[英]Non-zero distinct elements and indices in an array in Python
我有一個shape (3,3)
的數組A
。 我想識別所有非零不同元素及其索引。 我提出了預期的輸出。
import numpy as np
A=np.array([[10,2,0],[2,20,1.3],[0,1.3,30]])
預期的輸出是
Distinct=[10,2,20,1.3,30]
Indices=[[(0,0)],[(0,1),(1,0)],[(1,1)],[(1,2),(2,1)],[(2,2)]]
也許不是最漂亮的選擇,但這確實有效。
import numpy as np
A=np.array([[10,2,0],[2,20,1.3],[0,1.3,30]])
Distinct=sorted(set(list(np.reshape(A,A.shape[0]*A.shape[1]))))
Distinct = [x for x in Distinct if x!=0]
Indices = [[] for x in Distinct]
for i,x in enumerate(Distinct):
for j in range(A.shape[0]):
for k in range(A.shape[1]):
if x==A[j,k]:
Indices[i].append((j,k))
或者一個 numpy 解決方案,從 Kilian 的解決方案中汲取靈感:
import numpy as np
A=np.array([[10,2,0],[2,20,1.3],[0,1.3,30]])
Distinct = np.unique(A[A!=0])
Indices = [np.argwhere(A==x) for x in Distinct]
干得好!
import numpy as np
A = np.array([[10,2,0], [2,20,1.3], [0,1.3,30]])
indices = np.argwhere(A!=0)
distinct = np.unique(A[A!=0])
print(indices)
print(distinct)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.