1

I have a lists

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] 

I want to iterate to access 1, 4, 7, 10, then 2, 5, 8, 11, and then 3, 6, 9, 12. How to make this iteration?

Tiffany Arasya
  • 99
  • 1
  • 1
  • 9
  • 2
    kindly post how the output should look ... ```list(zip(*A))``` ? – sammywemmy May 01 '20 at 00:38
  • yess, 1, 4, 7, 10 (\n) 2, 5, 8, 11 (\n) 3, 6, 9, 12 (\n) – Tiffany Arasya May 01 '20 at 00:40
  • try a combination of [zip](https://docs.python.org/3.3/library/functions.html#zip) and [chain(from itertools)](https://docs.python.org/3.8/library/itertools.html#itertools.chain.from_iterable) : ```list(chain.from_iterable(zip(*A)))``` – sammywemmy May 01 '20 at 00:41

2 Answers2

1

You can access them using

for i in range(len(A[0])):
    for j in range(len(A)):
        print(A[j][i])
Tom Planche
  • 116
  • 11
0

If you can use something that’s not in the standard library, numpy is a good tool for modifying lists and matrices. You can do something like the following:

import numpy as np

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] 

print(np.asarray(A).T)
RohanP
  • 352
  • 1
  • 5