2017-09-06 125 views
0

我必须解决如何更换零个以下元素中的元素用零和输出矩阵中的其余元素的总和。更改矩阵难题的特定元素 - 的Python

例如,[[0,3,5],[3,4,0],[1,2,3]]应该输出的3 + 5 + 4 + 1 + 2的总和,这是15 。

到目前为止:

def matrixElementsSum(matrix): 
    out = 0 
    # locate the zeros' positions in array & replace element below 
    for i,j in enumerate(matrix): 
     for k,l in enumerate(j): 
       if l == 0: 
       break 
      out += l 
    return out 

代码输出看似随机数。 有人能解决什么问题?感谢

回答

1

可以容易地丢弃是一个零元素下面的元素是通过使用the zip function

def matrixElementsSum(matrix): 
    out = 0 
    # locate the zeros' positions in array & replace element below 
    for i,j in enumerate(matrix): 
     # elements in the first row cannot be below a '0' 
     if i == 0: 
      out += sum(j) 
     else: 
      k = matrix[i-1] 
      for x, y in zip(j, k): 
       if y != 0: 
        out += x 
    return out 

现在考虑为变量命名更有意义。喜欢的东西:

def matrixElementsSum(matrix): 
    out = 0 
    # locate the zeros' positions in array & replace element below 
    for row_number, row in enumerate(matrix): 
     # elements in the first row cannot be below a '0' 
     if row_number == 0: 
      out += sum(row) 
     else: 
      row_above = matrix[row_number - 1] 
      for element, element_above in zip(row, row_above): 
       if element_above != 0: 
        out += element 
    return out 

你应该看看list comprehensions使连代码更易读。

+0

太感谢你了,正是我提出请求,并感谢指针。另外,你将如何做到阻止下面的所有行? – Tarae