Home > Software design >  How would I 'move' up or down through a 2d array
How would I 'move' up or down through a 2d array

Time:09-21

For example you are given the array:

array = [[2, 1, 4],
         [1, 3, 7],
         [7, 1, 4]]

and want to print each vertical column as a separate list:

res1 = [2, 1, 7]
res2 = [1, 3, 1]
res3 = [4, 7, 4]

what would be the most efficient way to code this for any size 2d array?

CodePudding user response:

If your 2D array is large and want lots of computation on it, better let numpy handle it

import numpy as np
array = np.array([[2, 1, 4],
                  [1, 3, 7],
                  [7, 1, 4]])

for col in array.T:
    print(col)

CodePudding user response:


for i in range(len(array[0])):
    print("Row {} : {}".format(i 1, array[i]))

Output

Row 1 : [2, 1, 4]
Row 2 : [1, 3, 7]
Row 3 : [7, 1, 4]

CodePudding user response:

You can use this code,

for x in range(len(array)):
   print("Row",x 1,":",array[x])
  • Related