2016-01-17 74 views
0

我是Python編程新手。我有這個任務:Python基本編程 - 二維列表

對於本實驗,您將使用Python中的二維列表。執行以下操作:

  1. 寫出一個用下面的頭 DEF sumColumn返回所有元素的和在一個指定列以矩陣的函數(矩陣,columnIndex)
  2. 寫功能,顯示逐行顯示矩陣中的元素,其中每行中的值顯示在單獨的行上(請參見下面的輸出)。輸出的格式必須與示例輸出中的格式相匹配,其中行的值由單個空格分隔。

  3. 編寫讀取3×4矩陣並顯示每列總和的測試程序(即主函數)。總和的格式應爲小數點後一位有效數字。必須按照下面的示例程序運行,輸入來自用戶的輸入,其中輸入逐行讀取,並且行中的值由單個空格分隔。

示例程序運行如下:

輸入一個3乘4矩陣行0列:2.5 3 4 1.5 輸入一個3乘4矩陣行對行1:1.5 4 2 7.5 輸入一個3乘4矩陣行對行2:3.5 1 1 2.5

的矩陣是 2.5 3.0 4.0 1.5 1.5 4.0 2.0 7.5 3.5 1.0 1.0 2.5

元素的總和爲colu MN 0是7.5 薩姆爲第1列的元素爲第2列元素的8.0 薩姆爲第3列的元素爲7.0 薩姆是11.5

下面是代碼我迄今爲止:

def sumColumn(matrix, columnIndex): 
    total = (sum(matrix[:,columnIndex]) for i in range(4)) 
    column0 = (sum(matrix[:,columnIndex]) for i in range(4)) 

    print("The total is: ", total) 
    return total 

def main(): 
    for r in range(3): 
     user_input = [input("Enter a 3-by-4 matrix row for row " + str(r) + ":",)] 
     user_input = int() 


    rows = 3 
    columns = 4 
    matrix = [] 
    for row in range(rows): 
     matrix.append([numbers] * columns) 
     print (matrix) 

main() 

it prints out: 
[[0, 0, 0, 0]] 
[[0, 0, 0, 0], [0, 0, 0, 0]] 
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 

我在做什麼錯?

+1

*我有這樣的任務*是立即關閉。 –

回答

0

你或許應該只是以這個爲參考,否則你永遠也學不到什麼東西

PROMPT = "Enter a 3-by-4 matrix row for row %s:" 

def sumColumn(matrix, columnIndex): 

    return sum([row[columnIndex] for row in matrix]) 

def displayMatrix(matrix): 

    #print an empty line so that the programs output matches the sample output 
    print 

    print "The matrix is" 
    for row in matrix: 
     print " ".join([str(col) for col in row]) 

    #another empty line 
    print 

    for columnIndex in range(4): 
     colSum = sumColumn(matrix, columnIndex) 
     print "Sum of elements for column %s is %s" % (columnIndex, colSum) 

def main(): 

    matrix = [map(float, raw_input(PROMPT % row).split()) for row in range(3)] 
    displayMatrix(matrix) 

if __name__ == "__main__": 
    main()