BirdKr - 4 months ago 19
Python Question

Python: List of List: switching entry positions

Suppose I create a list of list of integers to reflect a 3 x 3 matrix:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] to reflect the matrix:

1 2 3

4 5 6

7 8 9

In math literature and readings, we usually refer entries of a matrix in (x,y) form. So if we wanted to know the entry in the 1st row, 3rd column, we would consider (0, 2) entry of the matrix, the entry being the value 3.

Naturally one could mistake matrix[0][2] to be the same as well when it actually returns the value 7. To get the value 3, we would have to switch the list entry positions to matrix[2][0].

Besides manipulating the construction of the matrix, creating another data structure, or creating another list of list, is there a way in Python to switch the entry positions? so that:

modifiedList[x][y] == originalList[y][x]

You can use zip :

Make an iterator that aggregates elements from each of the iterables

``````list(zip(*matrix))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
``````

`*` is used to pass list of elements (unpacking the arguments), rather than single list. So the effect of `*` above is that, the arguments of zip will be: (1, 4, 7), (2, 5, 8), (3, 6, 9), that is:

``````list(zip((1, 4, 7), (2, 5, 8), (3, 6, 9))
``````