0

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]

2 Answers2

1

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))
DurgaDatta
  • 3,952
  • 4
  • 27
  • 34
0

That's known as a transposition. If you're using numpy ndarray, all you need is to call ndarray.transpose to get a view with the axis swapped. If you really want the list of lists form, it's not that hard to do a transposition:

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

Note that numpy's view does what you ask for, give a view that doesn't alter the underlying data structure but only the indexing. The zip way creates a full set of new lists. You could also create a proxy object that has getitem mapped to another behaviour, but numpy already has that in a more efficient form (for numeric matrices).

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26