0

我正在尝试创建一个函数,其中用户输入 3x4 2-D 列表的值,然后该函数打印数字网格,以及底部的额外行以及每列的总和。目前,我什至无法让它接受任何输入而不会出错。这是我到目前为止所得到的,最后没有添加列。

def testMatrixFunctions():
row0 = raw_input("Enter a 3-by-4 matrix row for row 0: ")
row0.split()
map(float, row0.split())
[float(c) for c in row0.split()]
row1 = raw_input("Enter a 3-by-4 matrix row for row 1: ")
row1.split()
map(float, row1.split())
[float(c) for c in row1.split()]
row2 = raw_input("Enter a 3-by-4 matrix row for row 2: ")
row2.split()
map(float, row2.split())
[float(c) for c in row2.split()]
print row0
print row1
print row2
4

1 回答 1

0

您可以使用 numpy 获取列总和

import sys
import numpy

ROWS = 3
COLS = 4

def main():

    global ROWS
    global COLS
    matrixData = []

    # Get input and process it
    for i in range(0, ROWS):
        thisRow = raw_input('Enter a 3-by-4 matrix row for row ' + str(i) + ' : ').split()
        evalRow = []
        [evalRow.append(eval(element)) for element in thisRow]      
        matrixData.append(evalRow)          

    numpyMatrix = numpy.array(matrixData)
    colSums = []
    [colSums.append(numpy.sum(numpyMatrix[:,index])) for index in range(0,COLS)]

    # Print the matrix
    for row in matrixData:
        print row
    print colSums
    return

if __name__ == '__main__':
    main()
    sys.exit(0)
于 2013-09-05T01:35:46.040 回答