来自文件python的矩阵的ColSum

时间:2014-10-22 03:19:03

标签: python list

我正在尝试计算列表列的列总和。我以前用于循环,我仍然无法计算。应该适用于任何大小的列表。我不能使用numpy或类似的东西。

数字

1 5 3
8 6 2
6 2 7

这是代码

def main():
    filNam = "matrix8.txt"
    matrix = (readMatrix(filNam))
    rowNum = 0
    colNum = 0
    print(matrix)
    (colSum(matrix, colNum))

def readMatrix(filNam):
    matrixList = []
    numFile = open(filNam, "r")
    lines = numFile.readlines()
    for line in lines:
        line = line.split()
        row = []
        for i in line:
            row.append(int(i))
        matrixList.append(row)
    return matrixList

def eachNumPresent(matrix):
    if len(matrix) % 2 != 0:
        return False
    else:
        return True

def rowSum(matrix, rowNum):
    for i in matrix[rowNum]:
        i = sum(matrix[rowNum])
        rowNum += 1
        print(i)

def colSum(matrix, colNum):
    for j in matrix[colNum]:
        total = 0
        for i in matrix:
            total += matrix[i][j]
        print(total)

main()

2 个答案:

答案 0 :(得分:0)

  1. 读取文件中的数字并使用列表理解

    构建矩阵
    >>> with open("Input.txt") as in_file:
    ...     matrix = [[int(num) for num in line.split()] for line in in_file]
    ...     
    ... 
    >>> matrix
    [[1, 5, 3], [8, 6, 2], [6, 2, 7]]
    
  2. 使用zip函数转置matrix,以便行成为列,反之亦然。

    >>> matrix  = zip(*matrix)
    >>> matrix
    [(1, 8, 6), (5, 6, 2), (3, 2, 7)]
    
  3. 事实上,而不是第2步,你可以在同一行找到列的总和,就像这样

    >>> sums = [sum(row) for row in zip(*matrix)]
    >>> sums
    [15, 13, 12]
    
  4. 修改:由于不允许zip,您可以像这样推送自己的zip功能

    >>> def transpose(matrix):
    ...     return [[matrix[j][i] for j, column in enumerate(row)] for i, row in enumerate(matrix)]
    ... 
    >>> 
    >>> with open("Input.txt") as in_file:
    ...     matrix = [[int(num) for num in line.split()] for line in in_file]
    ...     
    ... 
    >>> [sum(row) for row in transpose(matrix)]
    [15, 13, 12]
    >>> 
    

    由于也不允许enumerate,您可以使用普通for循环找到列的总和,如下所示

    >>> def get_column_sums(matrix):
    ...     result = [0] * len(matrix[0])
    ...     for i in range(len(matrix)):
    ...         for j in range(len(matrix[i])):
    ...             result[j] += matrix[i][j]
    ...     return result
    ... 
    >>> 
    >>> get_column_sums(matrix)
    [15, 13, 12]
    

答案 1 :(得分:0)

看起来你试图让事情变得复杂。

为每个可用于累积值的列创建名称

col0 = 0
col1 = 0
col2 = 0

对于文件中的每一行,提取每个字符。

with open('file.txt') as f:
    for line in f:
        c0, c1, c2 = line.strip().split()

将每个字符添加到相应的名称

        col0 += int(c0)
        col1 += int(c1)
        col2 += int(c2)

我重音名称,故意没有使用变量因为: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables