消除python矩阵中的交叉(列表列表)

2024-05-29 03:20:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有这样一个输入平方矩阵:

    test_matrix7x7_v01 = [[1, 0, 1, 1, 1, 0, 0],
                          [0, 1, 0, 0, 0, 1, 1],
                          [1, 0, 1, 1, 0, 1, 0],
                          [1, 0, 1, 1, 1, 0, 1],
                          [1, 0, 0, 1, 1, 1, 0],
                          [0, 1, 1, 0, 1, 1, 1],
                          [0, 1, 0, 1, 0, 1, 1]] 

假设我想删除矩阵的一个“交叉点”(例如第一行和第一列)

我编写了一个正常工作的函数:

def eliminate_cross(_comp_matrix,i,j):
    size = len(_comp_matrix[0])
    print("eliminating cross")
    matrix_copy = deepcopy(_comp_matrix)
    # print("deleting row")
    matrix_copy.remove(_comp_matrix[j])
    # print("deleting column")
    for h in range(size-1):
        del matrix_copy[h][j]
    return matrix_copy

并且,使用上面报告的输入,给出:

[[1, 0, 0, 0, 1, 1],
 [0, 1, 1, 0, 1, 0],
 [0, 1, 1, 1, 0, 1],
 [0, 0, 1, 1, 1, 0],
 [1, 1, 0, 1, 1, 1],
 [1, 0, 1, 0, 1, 1]]

问题:是否有正确的方法进行此操作?智能方式还是单行内置指令


Tags: 函数testsizedef矩阵matrixprintcopy
3条回答

取消多行和列的选项如何

def eliminate(matrix, rows, cols):
    return [[c for j, c in enumerate(r) if j not in cols] for i,r in enumerate(matrix) if i not in rows]

print(eliminate(test_matrix7x7_v01, (0,), (0,)))

这至少好一点

def eliminate_cross(A, i, j):
    A = deepcopy(A)
    del A[i]
    for row in A:
        del row[j]
    return A

这里有一种可能性:

def remove_cross(A,i,j):
    return [row[:j] + row[(j+1):] for k,row in enumerate(A) if k != i]

相关问题 更多 >

    热门问题