【问题标题】:Multiply elements of inner lists as a list comprehension将内部列表的元素相乘作为列表理解
【发布时间】:2015-06-01 03:19:52
【问题描述】:

这可以使用列表理解在单行中完成吗?

lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
products = ?? (Multiple each list elements)

所需的输出 = [6, 24, 30, 9]

我试过类似的东西:

products = [l[i] * l[i + 1] for l in lst for i in range(len(l) - 1)]

但没用。

【问题讨论】:

  • 您是否还需要回答为什么您的方法不起作用?

标签: python list collections list-comprehension


【解决方案1】:

您可以使用reduce() 对整数列表进行乘法运算,同时使用operator.mul() 进行实际乘法运算:

from functools import reduce

from operator import mul

products = [reduce(mul, l) for l in lst]

在 Python 3 中,reduce() 已移至 functools.reduce(),因此支持 import 语句。由于functools.reduce 自 Python 2.6 以来就存在,如果您需要保持代码与 Python 2 和 3 兼容,从那里导入它会更容易。

演示:

>>> from operator import mul
>>> lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
>>> [reduce(mul, l) for l in lst]
[6, 24, 30, 9]

operator.mul() 可以换成lambda x, y: x * y 但是为什么要养一只狗自己吠呢?

【讨论】:

  • 赞成mul,我的想法相同,但改用lambda,这样更好。
【解决方案2】:

使用numpy的另一种方法

>>> from numpy import prod
>>> [prod(x) for x in lst] 
[6, 24, 30, 9]

参考 - Documentation on prod

【讨论】:

    【解决方案3】:

    试试:

    products = [reduce(lambda x, y: x * y, l) for l in lst]
    

    【讨论】:

      【解决方案4】:

      是的,您可以在列表理解中使用 reduce 和 lambda 表达式:

      >>> [reduce(lambda x, y: x * y, innerlst) for innerlst in lst]
      [6, 24, 30, 9]
      

      注意,在 Python 3 中,reduce 已移至 functools 模块,因此您必须从那里导入:

      from functools import reduce

      如果您不想使用 lambda 表达式,可以将其完全替换为 operator.mul

      【讨论】:

        【解决方案5】:

        使用this 解决方案为列表创建产品操作员,您可以执行以下操作:

            lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
            import operator
            from functools import reduce # Valid in Python 2.6+, required in Python 3
            def prod(numeric_list):
                return reduce(operator.mul, numeric_list, 1)
        
            [prod(l) for l in lst]
        

        输出:

            Out[1]: [6, 24, 30, 9]
        

        【讨论】:

          【解决方案6】:

          启动Python 3.8,并将prod函数添加到math模块:

          import math
          
          # lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9], []]
          [math.prod(l) for l in lst]
          # [6, 24, 30, 9, 1]
          

          请注意,空子列表将获得1 的产品值,该值由start 的值定义:

          math.prod(iterable, *, start=1)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-04-06
            • 1970-01-01
            • 1970-01-01
            • 2022-06-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多