Search code examples
pythonlistmultiple-columnstranspose

How to print a list into 4 columns horizontally and vertically (transposed)?


I have a list

list = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 39, 39, 44, 42, 40, 43, 47, 45, 57, 52, 75, 73, 86, 78, 70, 77, 87, 79, 113, 96, 147, 141, 170, 150, 130, 145, 167, 147, 225, 184]

and I am trying to get it to be returned in 4 columns horizontally

21    22    23    24
25    26    27    28
29    30    39    39
44    42    40    43
...

as well as vertically

21   39   75   147
22   39   73   141
23   44   86   170
24   42   78   150
25   40   70   130
26   43   77   145
27   47   87   167
28   45   79   147
29   57   113  225
30   52   96   184

This is my attempt at solving this horizontally:

# prints array in columns
def printArray(array):
    row = 10
    col = 4

    for i in range(row):
        for j in range(col):
            print(array[i][j], '\t', end="")

But it does not work.

I've also tried searching how to transpose the list some how but only found how to transpose a list of lists.

Transpose list of lists

Any help would be appreciated thank you.


Solution

  • Here are 2 functions that print both directions.

    Horizontal output:

    21      22      23      24      
    25      26      27      28
    29      30      39      39
    44      42      40      43
    47      45      57      52
    75      73      86      78
    70      77      87      79
    113     96      147     141
    170     150     130     145
    167     147     225     184
    

    Vertical output:

    21      39      75      147     
    22      39      73      141
    23      44      86      170
    24      42      78      150
    25      40      70      130
    26      43      77      145
    27      47      87      167
    28      45      79      147
    29      57      113     225
    30      52      96      184
    

    Code:

    data = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 39, 39, 44, 42, 40, 43, 47, 45, 57, 52, 75, 73, 86, 78, 70, 77, 87, 79, 113, 96, 147, 141, 170, 150, 130, 145, 167, 147, 225, 184]
    
    def print_horizontaly(lst: list, columns, spacing):
        for i, item in enumerate(lst):
            if i % columns == 0:
                print("")
    
            print(item, end=''.join(' ' for j in range(spacing - len(str(item)))))
            
    
    def print_verticaly(lst: list, columns, spacing):
        columns_ = []
        for i in range(len(lst)//columns):
            for item in lst[i::len(lst)//columns]:
                print(item, end=''.join(' ' for j in range(spacing - len(str(item)))))
    
            print("")
    
    
    print_horizontaly(data, 4, 8)
    print_verticaly(data, 4, 8)