pythonlistiterationmultiple-columns

How can I print the data in a grid-like list in columns instead of rows?


So I have this list called data_lst:

[1,2,3,4]
[3,2,4,1]
[4,3,1,2]

and I want my output to be the numbers by columns, like

[1,3,4]
[2,2,3]
[3,4,1]
[4,1,2]

I have attempted to do this so far...

f = []
for x in data_lst:
    for w in range(0,len(x)-1):
        f.append(data_lst[w])
print(f)

However, the output I'm getting is the same as the input I provided, which is..

[1,2,3,4]
[3,2,4,1]
[4,3,1,2]

What should I change in my code?


Solution

  • The operation is called transpose of a matrix. You can do it an variety of ways like using numpy, with zip etc. This is just a solution modifying your code.

    data_lst = [
      [1,2,3,4],
      [3,2,4,1],
      [4,3,1,2]
    ]
    
    
    rowLen = len(data_lst)
    colLen = len(data_lst[0])
    f = [[0 for _ in range(rowLen)] for _ in range(colLen)]
    for c in range(colLen):
        for r in range(rowLen):
            f[c][r] = data_lst[r][c]
    print(f)