【问题标题】:sum of first value in nested list嵌套列表中第一个值的总和
【发布时间】:2015-02-01 16:08:48
【问题描述】:

在传统 python 中,sum 函数给出了 list 的总和:

sum([0,1,2,3,4])=10

另一方面,如果你有一个嵌套列表怎么办:

sum([[1,2,3],[4,5,6],[7,8,9]])

我们发现错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

除此之外,我们如何在嵌套列表中找到第一个值(索引 0)的sum?如:

something([[1,2,3],[4,5,6],[7,8,9]])=12

【问题讨论】:

    标签: python list sum list-comprehension nested-lists


    【解决方案1】:

    要获得所有第一个元素的总和,您需要一个生成器表达式

    >>> a = [[1,2,3],[4,5,6],[7,8,9]]
    >>> sum(i[0] for i in a)
    12
    

    您收到 unsupported operand type(s) for +: 'int' and 'list' 是因为您尝试添加三个列表,这不是所需的行为。

    如果您想要一个第一个元素的列表,然后找到它们的总和,您可以尝试使用列表推导

    >>> l = [i[0] for i in a]
    >>> l
    [1, 4, 7]
    >>> sum(l)
    12
    

    或者您可以调用 __next__ 方法,因为列表是可迭代的(如果 Py3)

    >>> sum(zip(*a).__next__())
    12
    

    【讨论】:

      【解决方案2】:

      或者你可以使用zip

      >>> l=[[1,2,3],[4,5,6],[7,8,9]]
      >>> sum(zip(*l)[0])
      12
      

      【讨论】:

        【解决方案3】:

        您可以创建一个函数来查找嵌套列表的总和:

        def nested_sum(par):
            total = 0 
            for k in par:
                if isinstance(k, list):  # checks if `k` is a list
                    total += nested_sum(k)
                else:
                    total += k
            return total
        

        @Kasara 和 @Bhargav 也有一些巧妙的答案,看看吧!

        【讨论】:

          【解决方案4】:
          >>> sum(map(lambda x:x[0],[[1,2,3],[4,5,6],[7,8,9]]))
          12
          

          【讨论】:

            【解决方案5】:

            使用numpy,这样的事情很容易:

            In [16]: import numpy as np
            
            In [17]: a = [[1,2,3],[4,5,6],[7,8,9]]
            
            In [18]: my_array = np.array(a)
            
            In [19]: my_array[:,0].sum()
            Out[19]: 12
            

            【讨论】:

              【解决方案6】:

              对于python初学者:

              通过正常的for循环并使用try和except来处理最佳列表为空时的异常。

              >>> l = [[1,2,3],[4,5,6],[7,8,9], []]
              >>> result = 0
              >>> for i in l:
              ...     try:result += i[0]
              ...     except IndexError:pass
              ... 
              >>> result
              12
              >>> 
              

              【讨论】:

              • 不要使用旧式的except IndexError, e,它只是为了在 Python 2 中向后兼容而存在(在 Python 3 中被删除),使用:except IndexError as e。顺便说一句,你什么都不做,除了你可以简单地做:except IndexError
              • @AshwiniChaudhary:是的,谢谢你检查我的代码,现在更新了。
              猜你喜欢
              • 2018-05-30
              • 1970-01-01
              • 1970-01-01
              • 2018-08-02
              • 2018-06-16
              • 1970-01-01
              • 2020-05-17
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多