从 Python 中的二维数组打印时如何排列列?
How to line up columns when printing from 2d array in Python?
我想以表格格式显示一个简单的二维数组,标题位于顶部,以便值在标题下排列。有没有办法做到这一点?我看过 pprint 并使用 numpy 进行打印,但无法使其正常工作。这是我目前拥有的:
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 = ' ')
有什么建议吗?
您只需要根据最长元素的长度对齐即可:
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
我想以表格格式显示一个简单的二维数组,标题位于顶部,以便值在标题下排列。有没有办法做到这一点?我看过 pprint 并使用 numpy 进行打印,但无法使其正常工作。这是我目前拥有的:
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 = ' ')
有什么建议吗?
您只需要根据最长元素的长度对齐即可:
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