【问题标题】:Python calculating the sum of rows in a listPython计算列表中的行总和
【发布时间】:2017-08-23 10:00:18
【问题描述】:

我想编写一段代码来计算列表中每一行中元素的总和并返回行总和的新列表。例如

def row_sums(square):

    square = [
       [1, 2, 3, 4],
       [5, 6, 7, 8],
       [9, 10, 11, 12],
       [13, 14, 15, 16]
    ]
    print(row_sums(square))

这将给出[10, 26, 42, 58] 的输出,因为第一行的总和等于 10,第二行的总和等于 26,依此类推。但是我不想使用内置的 sum 函数来做到这一点。我该怎么做呢?提前致谢。

【问题讨论】:

  • “我不想使用内置的 sum 函数” 为什么不呢?
  • 我不认为你的代码会产生[10, 26, 42, 58]
  • 你知道如何求单行的总和吗?
  • How would I go about doing this? 常见的方法是编写代码来执行您想要的操作......而不是先在这里询问而不尝试任何事情。
  • @vaultah 这是家庭作业。找到一个骗子,快!

标签: python list


【解决方案1】:

一段简单的代码,用于计算列表每一行中元素的总和。

square = [
   [1, 2, 3, 4],
   [5, 6, 7, 8],
   [9, 10, 11, 12],
   [13, 14, 15, 16]
]
su=[sum(i) for i in square]
print (su)

输出:

[10, 26, 42, 58]

【讨论】:

    【解决方案2】:

    如果你真的不能使用 sum() 函数,这里有一个函数来对行求和,我已经明确地写了它来显示这些步骤,但是一旦你理解了发生了什么,就值得看看列表推导:

    def row_sums(square):
    
        # list to store sums
        output = []
    
        # go through each row in square
        for row in square:
    
            # variable to store row total
            total = 0
    
            # go through each item in row and add to total
            for item in row:
                total += item
    
            # append the row's total to the output list
            output.append(total)
    
        # return the output list
        return output
    

    然后可以这样使用:

    square = [
       [1, 2, 3, 4],
       [5, 6, 7, 8],
       [9, 10, 11, 12],
       [13, 14, 15, 16]
    ]
    
    row_totals = row_sums(square)
    

    编辑:

    为了回答您的评论,我会这样做:

    def sum_columns(square):
    
        # as before have a list to store the totals
        output = []
    
        # assuming your square will have the same row length for each row
        # get the number of columns
        num_of_columns = len(square[0])
    
        # iterate over the columns
        for i in xrange(0, num_of_columns):
    
            # store the total for the column (same as before)
            total = 0
    
            # for each row, get the value for the column and add to the column total
            # (value at index i)
            for row in square:
                total += row[i]
    
            # append the total to the output list
            output.append(total)
    
        # return the list of totals
        return output        
    

    【讨论】:

    • 感谢您的回复,不过我还有一个问题。我将如何调整此代码以在每列而不是行中添加元素?
    • 用答案编辑了我的问题,正如我之前提到的,我已经一步一步地写出来,这样你就可以看到逻辑,一旦你对它的工作方式感到满意,那就是值得看看其他一些更简洁的答案:)
    【解决方案3】:

    编写自己的求和函数...

    模块functools 有一个有用的reduce function,您可以使用它来编写自己的求和函数。如果您对 lambda functions 感到满意,您可以这样做:

    lst = [0,1,2,3,4,5]
    

    这将使sum(lst) 成为15。但是,您自己使用 reduce 的 sum 函数可能类似于:

    from functools import reduce
    
    reduce(lambda x,y: x + y, l)
    

    这也会给15。您应该能够自己编写其余部分(即在另一个处理行的列表中)。

    【讨论】:

      【解决方案4】:

      您也可以使用comprehensionreduce

      [reduce(lambda x, y: x + y, item) for item in square]
      

      【讨论】:

        【解决方案5】:

        您可以将这些行添加到现有函数中:

        result = []
        for row in square: # iterates trough a row
            line = 0 #stores the total of a line
        
            for num in row: #go trough every number in row
                line += num #add that number to the total of that line
        
            result.append(line) #append to a list the result
        
        print(result) #finally return the total of every line sum's in a list
        

        【讨论】:

          【解决方案6】:

          在某个时候你必须使用 sum 函数(作为 sum() 或 "+")但你可以使用 map 之类的

          list(map(sum, square))
          

          【讨论】:

            猜你喜欢
            • 2020-01-02
            • 1970-01-01
            • 2018-09-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-03-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多