我正在使用jupyter笔记本。我想以一般形式打印一个简单的整数矩阵,即我输出如下: a [0] [0] = 1 a [0] [1] = 2 a [1] [0] = 3 a [1] [1] = 4
这是我的计划:
column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
for j in range (0, column):
a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
for j in range (0, column):
print ("a[",i,"][",j,"] =",a[i][j],"\t",),
print ("\n")
但我得到的输出为:
Enter the number of columns: 2
Enter the number of rows: 2
Enter the elements: 1
Enter the elements: 2
Enter the elements: 3
Enter the elements: 4
a[ 0 ][ 0 ] = 1
a[ 0 ][ 1 ] = 2
a[ 1 ][ 0 ] = 3
a[ 1 ][ 1 ] = 4
循环中的print(),函数进入一个新行,即使我在它后面加了一个逗号。请帮我获得所需的输出格式。谢谢。
答案 0 :(得分:0)
这不会打印新行
print(something,end="")
和你的代码
column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
for j in range (0, column):
a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
for j in range (0, column):
print("a[%d][%d] = %d "%(i,j,a[i][j]),end="")
答案 1 :(得分:0)
其他答案都很好,但代码更易读:
some_string = ''
for i in range (0, row):
for j in range (0, column):
some_string += "a[{}][{}]= {} ".format(i,j,a[i][j])
print(some_string)