你好,假设我有一个二维数组 a = [[1,2,1,2], [3,4,5,3], [8,9,4,3]]
,我想将其打印在类似表格的网格中。到目前为止,我的代码是:
def printArray(a):
for row in range(len(a[0])):
for col in range (len(a[0])):
b = print("{:8.3f}".format(a[row][col]), end = " ")
print(b)
当它被打印出来时,它给我:
1.000 2.000 1.000 2.000 None
3.000 4.000 5.000 3.000 None
8.000 9.000 4.000 3.000 None
然后是错误:
File "hw8pr2.py", line 17, in printArray
b = print("{:8.3f}".format(a[row][col]), end = " ")
IndexError: list index out of range
有人能告诉我为什么会这样吗?我也不希望每行末尾的“无”。我希望它输出:
1.000 2.000 1.000 2.000
3.000 4.000 5.000 3.000
8.000 9.000 4.000 3.000
最佳答案
这是你正在使用的:
def printArray(a):
for row in range(len(a[0])):
for col in range (len(a[0])):
b = print("{:8.3f}".format(a[row][col]), end = " ")
print(b)
您在 len(a[0])
中使用了两个 for 循环,但您的输入数据不是正方形,因此无法正常工作!
你可以考虑使用这个:
def printA(a):
for row in a:
for col in row:
print("{:8.3f}".format(col), end=" ")
print("")
这会给你这个:
In [14]: a = [[1, 2, 1, 2], [3, 4, 5, 3], [8, 9, 4, 3]]
In [15]: printA(a)
1.000 2.000 1.000 2.000
3.000 4.000 5.000 3.000
8.000 9.000 4.000 3.000
In [16]: b = [[1, 2, 1, 2, 5], [3, 4, 7, 5, 3], [8, 2, 9, 4, 3], [2, 8, 4, 7, 6]]
In [17]: printA(b)
1.000 2.000 1.000 2.000 5.000
3.000 4.000 7.000 5.000 3.000
8.000 2.000 9.000 4.000 3.000
2.000 8.000 4.000 7.000 6.000
关于python - 如何以 "pretty"格式打印二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40441391/