如何在Python中打印3D数组?

时间:2017-03-24 10:55:38

标签: python

我在Python中创建了一个简单的3D数组,我需要在行中打印它。

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

我希望它打印如下:

SNo. Computers Mobile
1 iMac iPhone
2 Macbook iPod

3 个答案:

答案 0 :(得分:1)

该数据对我来说是2D。如果你真的想要打印3D数组,那么你可以避免自己编写任何循环并使用numpy

import numpy as np

apple_np = np.array(apple)
print apple_np

但您的数据不是3D,因此无法按照您的设想打印出来。你需要的是一个2D阵列:

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

apple_np = np.array(apple)
print apple_np

如果您使用的是python 2.7,则可以使用以下内容以漂亮的格式打印出表格:

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 ""

答案 1 :(得分:0)

你可以这样做:

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

但坦率地说,由于最终元素都是单元素列表,我认为你应该改变创建它的代码以开始使用2D数组。一切都会那么容易。

答案 2 :(得分:0)

它应该有效:

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 = []
相关问题