对于这个矩阵 K=
[[-1. 1. 0.]
[ 0. 0. 0.]
[ 0. -1. 1.]
[ 0. 0. 0.]
[ 0. -1. 1.]
[ 0. 0. 0.]]
任务是将非零唯一行的索引存储在一个数组中(这里的答案是{0,2}),这样
K([0,2],:)
可用于线性代数运算。 我的尝试是:
myList = []
for i in range(len(K)): #generate pairs
for j in range(i+1,len(K)): #travel down each other rows
if np.array_equal(K[i],K[j]) and np.any(K[i] != 0, axis=1) and np.any(K[j] != 0, axis=1):
myList.append(K[i])
print ('indices of similar-non-zeros rows are\n',(i, j)),
elif not np.array_equal(K[i],K[j]) and np.any(K[i] != 0,axis=1) and np.any(K[j] != 0, axis=1):
myList.append(K[i])
print ('indices of non-similar-non-zeros rows are\n',(i, j)),
else:
continue
new_K = np.asmatrix(np.asarray(myList))
new_new_K = np.unique(new_K,axis=0)
print('Now K is \n',new_new_K)
答案是:
new_new_K = [[-1. 1. 0.]
[ 0. -1. 1.]]
问题1:如何用pythonic方式实现。以上是具有矩阵存储限制的替代解决方案,但更可取的是将索引存储在数组中。
最佳答案
为此,您可以使用带有 enumerate
的简单 for
循环。
import numpy as np
A = np.array([[-1, 1, 0],
[ 0, 0, 0],
[ 0, -1, 1],
[ 0, 0, 0],
[ 0, -1, 1],
[ 0, 0, 0]])
seen = {(0, 0, 0)}
res = []
for idx, row in enumerate(map(tuple, A)):
if row not in seen:
res.append(idx)
seen.add(row)
结果
print(A[res])
[[-1 1 0]
[ 0 -1 1]]
示例#2
import numpy as np
A=np.array([[0, 1, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1],
[1, 1, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0]])
seen={(0, )*6}
res = []
for idx, row in enumerate(map(tuple, A)):
if row not in seen:
res.append(idx)
seen.add(row)
print(A[res])
# [[0 1 0 0 0 1]
# [0 0 0 1 0 1]
# [1 0 1 0 1 1]
# [1 1 1 0 0 0]
# [0 1 0 1 0 1]]
关于Python:在将每一行与矩阵中的每一行进行比较后存储非零唯一行的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49857395/