首页 > 解决方案 > Swapping columns of a matrix without numpy

问题描述

I need to swap the columns of a given matrix by applying some function to (M,i,j) to swap the ith and jth columns of M.

def swap_columns(M,i,j)
    rows = M[i]
    col = M[i][j]
    for i in M:
        N = M[i][j]
        M[i][j] = M[j][i]
        M[j][i] = N
    return N

Unable to get this working at all.

标签: python

解决方案


In python variable swapping can be done by: x, y = y, x

Code:

This function will modify the original matrix. No need to return

def col_swapper(matrix, col_1, col_2):
    for line in range(len(matrix)):
        matrix[line][col_1], matrix[line][col_2] = matrix[line][col_2], matrix[line][col_1]

推荐阅读