几乎已解决,但无法弄清楚如何排除第三列数字后的空白。下面的代码:
mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]
for row, nums in enumerate(mult_table):
for column, num in enumerate(nums):
print(num, end = ' ')
if column == len(mult_table)-1:
print()
else:
print('| ', end = '')
您的输出(包括第3列后的空白)
1 | 2 | 3 2 | 4 | 6 3 | 6 | 9
预期的输出(第3列后不应包含空格)
1 | 2 | 3 2 | 4 | 6 3 | 6 | 9
答案 0 :(得分:0)
使用str.join()
构建该字符串,例如:
' | '.join(str(x) for x in row)
mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]
for row in mult_table:
print(' | '.join(str(x) for x in row))
1 | 2 | 3
2 | 4 | 6
3 | 6 | 9