Search code examples
pythonnumpynumpy-ndarraynumpy-slicing

Printing columns of a list of arrays


I have the following list

import numpy as np
Y = [np.array([[1, 4, 7],
        [2, 5, 8]]),
 np.array([[10, 14, 18],
        [11, 15, 19],
        [12, 16, 20],
        [13, 17, 21]]),
 np.array([[22, 26, 31],
        [24, 28, 33],
        [26, 30, 35]])]

I want to loop through and print the columns inside of all the arrays in Y.

I don't know how to access the columns of Y. Running Y[:,0] for example, does not give me

[[1]
 [2]]

Instead, it gives me the following error

TypeError: list indices must be integers or slices, not tuple

I want to print all columns of all the arrays in Y, not just the first column of the first array.


Solution

  • Does this help?

    for i in range(3):
        l = Y[i]
        for j in range(len(np.transpose(l))):
            print(l[:,j])
    

    This gives you:

    [1 2]
    [4 5]
    [7 8]
    [10 11 12 13]
    [14 15 16 17]
    [18 19 20 21]
    [22 24 26]
    [26 28 30]
    [31 33 35]