2017-06-05 126 views
0

我正在使用jupyter筆記本。我想打印一個簡單的整數矩陣的一般形式,即我不能輸出是這樣的: a [0] [0] = 1 a [0] [1] = 2 a [1] [0 ] = 3 [1] [1] = 4Python中的'print'命令(打印在同一行中)

這是我的程序:

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 

打印(),函數的循環即使我在後面加了一個逗號,也會換個新的行。請幫助我獲得所需的輸出格式。謝謝。

+3

是這個Python 2或Python 3? –

+0

@Rawing由於括號不會顯示在輸出中,我們必須得出結論,它是python 3(或者'print_function'在python 2中使用)。 – Leon

+4

'print()'*函數*(來自Python 3)與Python 2中的'print' *語句*的用法不同。在*函數中*使用'end =「」'參數來抑制換行結束。 – cdarke

回答

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="") 
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)