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