I have a simple list of lists called square
:
square = [[1,2,3],[4,5,6],[7,8,9]]
and my goal is to iterate through each of the nine elements and get all the values in that element's row and column simultaneously. In this example, the first iteration (for element 1) should return [1,2,3]
and [1,4,7]
, the second (for element 2) would give me [1,2,3]
and [2,5,8]
, etc. The following code works:
for r in range(3):
for c in range(3):
row = square[r]
col = [square[c1][c] for c1 in range(3)]
but is there another method using base Python to do this?
I can transpose and iterate over the list using for c in zip(*square):
, which works if I just need the columns once, but is there no way to use array slicing to index the columns without storing the transpose of the matrix as well as the matrix itself?
Unfortunately, libraries like numpy aren't an option at the moment because they'll need to go through our code review process first, which takes a long time (on the order of six months...). I didn't write the policy or design the procedures, but it's the policy I have to work with at this institution. I already filed the request for numpy, but in the meantime, I'm just using base Python.