4

我想以表格格式显示一个简单的二维数组,顶部有标题,以便值在标题下排列。有没有办法做到这一点?我已经使用 numpy 查看了 pprint 和打印,但无法使其正常工作。这是我目前所拥有的:

myArray = [['Student Name','Marks','Level'],['Johnny',68,4],['Jennifer',59,3],['William',34,2]]

for row in myArray:
    print(" ")
    for each in row:
        print(each,end = ' ')

有什么建议么?

4

1 回答 1

3

您只需要根据最长元素的长度进行对齐:

myArray = [['Student Name','Marks','Level'],['Johnny',68,4],['Jennifer',59,3],['William',34,2]]
mx = len(max((sub[0] for sub in myArray),key=len))

for row in myArray:
    print(" ".join(["{:<{mx}}".format(ele,mx=mx) for ele in row]))

输出:

Student Name Marks        Level       
Johnny       68           4           
Jennifer     59           3           
William      34           2 

要在最大长度计算中包含 int 值:

mx = max((len(str(ele)) for sub in myArray for ele in sub))
for row in myArray:
    print(" ".join(["{:<{mx}}".format(ele,mx=mx) for ele in row]))

输出:

Student Name Marks        Level       
Johnny       68           4           
Jennifer     59           3           
William      34           2       
于 2015-07-22T15:09:02.350 回答