Python基本编程-2D列表

Python基本编程-2D列表,python,list,function,matrix,Python,List,Function,Matrix,我是Python编程新手。我的任务是: 对于本实验室,您将使用Python中的二维列表。请执行以下操作: 编写一个函数,使用以下标题返回矩阵中指定列中所有元素的总和 def SUM列(矩阵、列索引) 编写一个函数,逐行显示矩阵中的元素,其中每行中的值显示在单独的行上(请参见下面的输出)。输出的格式必须与示例输出中的格式匹配,其中行上的值由单个空格分隔 编写一个测试程序(即主函数),读取一个3 X 4矩阵并显示每列的总和。总和的格式应确保在小数点后正好包含一个有效数字。来自用户的输入必须在下面运行

我是Python编程新手。我的任务是:

对于本实验室,您将使用Python中的二维列表。请执行以下操作:

  • 编写一个函数,使用以下标题返回矩阵中指定列中所有元素的总和 def SUM列(矩阵、列索引)
  • 编写一个函数,逐行显示矩阵中的元素,其中每行中的值显示在单独的行上(请参见下面的输出)。输出的格式必须与示例输出中的格式匹配,其中行上的值由单个空格分隔

  • 编写一个测试程序(即主函数),读取一个3 X 4矩阵并显示每列的总和。总和的格式应确保在小数点后正好包含一个有效数字。来自用户的输入必须在下面运行的示例程序中输入,其中输入逐行读取,行中的值用单个空格分隔

  • 示例程序运行如下所示:

    为第0行输入3×4矩阵行:2.5 3 4 1.5 为第1行输入一个3乘4的矩阵行:1.5 4 2 7.5 为第2行输入一个3乘4的矩阵行:3.5 1 2.5

    矩阵是 2.5 3.0 4.0 1.5 1.5 4.0 2.0 7.5 3.51.01.02.5

    第0列的元素之和为7.5 第1列的元素总和为8.0 第2列的元素总和为7.0 第3列的元素总和为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]]
    

    我做错了什么?

    你也许应该把它作为参考,否则你永远也学不到任何东西

    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()
    
    我有这个任务是立即关闭。