0

I created a simple 3D array in Python I need to print it in rows.

apple=[[["SNo."],["Computers"],["Mobile"]],
       [["1"],["iMac"],["iPhone"]],
        [["2"],["Macbook"],["iPod"]]]

I want it to be printed like below:

SNo. Computers Mobile
1 iMac iPhone
2 Macbook iPod
1
  • How do you need it to look? Commented Mar 24, 2017 at 10:59

3 Answers 3

2

You can do that with:

for l in apple:
    print(*[e[0] for e in l])

But frankly, since the final elements are all one-element list, I think you should change the code that creates it to have a 2D array to start with. Everything will be easier that way.

Sign up to request clarification or add additional context in comments.

Comments

1

That data looks 2D to me. If you really want to print a 3D array, then you can avoid writing any loops yourself and use numpy:

import numpy as np

apple_np = np.array(apple)
print apple_np

Your data, however isn't 3D, so it won't print out as you envisage. What you need is a 2D array:

apple=[["SNo.", "Computers", "Mobile"],
       ["1", "iMac", "iPhone"],
       ["2", "Macbook", "iPod"]]

apple_np = np.array(apple)
print apple_np

If you're using python 2.7, you can use the following to print out the table in a nice format:

width = max([len(el) for row in apple for el in row]) + 1

for row in apple:
    for el in row:
        print ("{:"+str(width)+"s}").format(el),
    print ""

Comments

0

it should works:

for i in apple:
    for j in i:
        helper.append(j)
    counter = 0
    assistant = []
for x in helper:
    counter += 1
    assistant.append(x[0])
    if counter == 3:
        print(" ".join(assistant))
        counter = 0
        assistant = []

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.