Python 2D列表添加列的值

时间:2015-08-25 15:11:02

标签: python

所以我必须使用函数def sumColumn(matrix,columnIndex)来添加由用户输入的行创建的列的值,并且我不能完全弄清楚从这一点开始做什么。

def sumColumn(matrix, columnIndex):
    return

def getMatrix():
    matrix = []
    for row in range(3):
        print("Enter a 3-by-4 matrix row for row:%d" %row)
        row = input().split(' ')
        row = [float(i) for i in row]
        matrix.append(row)
    return matrix

def display(m):
    for row in m:
        print(row)

def main():
    m = getMatrix()
    print("\nThe matrix is")
    display(m)
    print()
    for col in range(len(m[0])):
        print("Sum of elements for column %d is %.2f" % (col, sumColumn(m,col)))

main()

4 个答案:

答案 0 :(得分:0)

如果您可以使用.sum(),则可以在列

上使用import numpy as np def sumColumn(matrix, columnIndex): matrix = np.array(matrix) return matrix[:,columnIndex].sum()
Enter a 3-by-4 matrix row for row:0
'1 2 3 4'
Enter a 3-by-4 matrix row for row:1
'1 2 3 4'
Enter a 3-by-4 matrix row for row:2
'1 2 3 4'

The matrix is
[1.0, 2.0, 3.0, 4.0]
[1.0, 2.0, 3.0, 4.0]
[1.0, 2.0, 3.0, 4.0]

Sum of elements for column 0 is 3.00
Sum of elements for column 1 is 6.00
Sum of elements for column 2 is 9.00
Sum of elements for column 3 is 12.00

其中给出了以下输出:

{{1}}

答案 1 :(得分:0)

def sumColumn(matrix, columnIndex):
    sum = 0                     # running sum
    for row in matrix:
        sum += row[columnIndex] # add value from specified column of row to sum
    return sum

答案 2 :(得分:0)

您可以使用sum函数和生成器表达式从矩阵中的每一行获取该索引处的元素:

def sumColumn(matrix, columnIndex):
    return sum(row[columnIndex] for row in matrix)

答案 3 :(得分:0)

你永远不会控制每一行都有相同数量的列,这可能导致以后的错误。

假设输入正确,您可以这样做:

def sumColumn(matrix, columnIndex):
    sum = 0
    for i in range(len(matrix)):
        sum += matrix[i][columnIndex]
    return sum

但是,请务必双重控制输入!