Mart
Mart

Reputation: 21

How to get columns out of any length of list?

This question may been asked before, but I couldn't find the answer that I need. I'm interested in getting columns out of any length of a list. I know how to do it only with certain length.

I have to check two matrixes and if one of these is the transpose of another. Since they can vary in length its not so easy for me.

matrix_1 = [[1, 2], [3, 4], [5, 6]]
matrix_2 = [[1, 3, 5], [2, 4, 6]]

This should return True.

Upvotes: 1

Views: 40

Answers (3)

Mart
Mart

Reputation: 21

Thanks for the answers, but i managed to solve my problem myself. Sorry for wasting your time. The solution is really simple, but i just tried too hard to solve this. Anyway if anyone intrested:

def is_transpose(matrix_1, matrix_2):

    for i in range(len(matrix_1)):
        for j in range(len(matrix_1[i])):
            if matrix_1[i][j] != matrix_2[j][i]:
                return False
    return True

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

pure python answer: zip to transpose (a classic), then convert to list (since zip yields tuples, so comparison would always fail), then compare:

matrix_1 = [[1, 2], [3, 4], [5, 6]]
matrix_2 = [[1, 3, 5], [2, 4, 6]]

matrix_1 == [list(x) for x in zip(*matrix_2)]

Upvotes: 2

jpp
jpp

Reputation: 164783

Since you mention matrices, you should use 3rd party library numpy:

import numpy as np

matrix_1 = np.array([[1, 2], [3, 4], [5, 6]])

matrix_2 = np.array([[1, 3, 5], [2, 4, 6]])

res = np.array_equal(matrix_1, matrix_2.T)  # True
res = (matrix_1 == matrix_2.T).all()        # True

Upvotes: 2

Related Questions