Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading