【问题标题】:Reduce list based on index根据索引减少列表
【发布时间】:2013-03-01 07:38:57
【问题描述】:

假设我有 3 个列表

x1 = [1, 2, 3, 4]
x2 = [2, 3, 4, 5]
x3 = [3, 4, 5, 6]

我想根据索引减少这个列表。

我们可以通过对元素求和来减少这种情况:-x1[i] + x2[i] + x3[i]

out = [6, 9, 12, 15]

或乘法:-x1[i] * x2[i] * x3[i]

out = [6, 24, 60, 120]

python 中最好的方法是什么?

编辑:

有没有办法为列表列表执行此操作?

【问题讨论】:

    标签: python list reduce


    【解决方案1】:

    您可以使用zip 和sum 函数。

    out = [sum(i) for i in zip(x1, x2, x3)]
    

    对于乘法,您可以使用 reduce(适用于 Python 2)

    out = [reduce(lambda a, b: a * b, i) for i in zip(x1, x2, x3)]
    

    您可以在 Python 3 中从 functools 获取 reduce。

    不过,您也可以定义自己的乘法函数,然后在列表推导中使用该函数。

    def mult(lst):
        mul = 1
        for i in lst:
            mul *= i
        return mul
    
    out = [mult(i) for i in zip(x1, x2, x3)]
    

    如果您有列表列表lst = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]],那么您只需将zip(x1, x2, x3) 替换为zip(*lst)。 * 运算符基本上解包列表的元素并将它们作为单独的参数提供给函数。

    例如:

    out = [sum(i) for i in zip(*lst)]
    

    【讨论】:

      【解决方案2】:

      使用zip(*data):

      data = [
      [1, 2, 3, 4],
      [2, 3, 4, 5],
      [3, 4, 5, 6]
      ]
      
      print [sum(col) for col in zip(*data)]
      
      import operator
      def product(data):
          return reduce(operator.mul, data)
      
      print [product(col) for col in zip(*data)]
      

      如果你想用非常大的数据进行计算,我建议你使用 NumPy:

      import numpy as np
      
      print np.sum(data, axis=0)
      print np.product(data, axis=0)
      

      【讨论】:

        猜你喜欢
        • 2021-01-09
        • 2015-11-30
        • 2014-03-16
        • 2014-01-28
        • 2019-06-18
        • 2014-09-24
        • 2019-12-10
        • 1970-01-01
        相关资源
        最近更新 更多