如何获取矩阵的特定行和该行的所有列?在 Python

How do I get specific rows of a matrix and all columns of this rows? in Python

我有一个位向量 B[] 和一个矩阵 NxN。我想获取矩阵中 B[] 向量中的位为 1 的所有行。例如:

基本for循环:

b = [1,0,1,1]
Matrix = [['a','b','c','d'],['e','f','g','h'],['i','j','k','l'],['m','n','o','p']]

result_matrix = []
for i in range(len(b)):
    if b[i] == 1:
        result_matrix.append(Matrix[i])
print (result_matrix)

什么是相等列表理解:

result_matrix = [Matrix[i] for i in range(len(b)) if b[i]]
print (result_matrix)

出于各种原因,我建议使用 numpy 数组。您可以使用真正的多维数组。比你将能够使用以下

对于 select 矩阵的特定行,您可以使用:

b(4,:)

如果条件是返回逻辑列表的函数,您可以显示满足条件的所有行:

b(condition(),:)

在您的情况下,您可以使用:

result_matrix = Matrix[b[:,0] == 1,:]