【问题标题】:Product of every element of two linear arrays [duplicate]两个线性数组的每个元素的乘积[重复]
【发布时间】:2019-03-11 09:22:05
【问题描述】:

如何将两个线性数组的每个元素相乘,即如果我得到这两个数组:

x=[1, 4, 0 ,3]
y=[2, 1, 9 ,4]

我想得到以下输出:

z=[2, 4, 0, 12]

【问题讨论】:

  • 如果你想像看起来那样使用 numpy,你需要将它们定义为 numpy 数组,所以:np.array([1, 4, 0 ,3])。然后你只需要将它们相乘(*

标签: python list


【解决方案1】:

使用list comprehension 是一种方法;使用zip 同时遍历两个列表:

z = [a * b for a, b in zip(x, y)]

另一种方法是使用numpy

import numpy as np

x = np.array([1, 4, 0 ,3])
y = np.array([2, 1, 9 ,4])

z = x * y
print(z)  # [ 2  4  0 12]

【讨论】:

    【解决方案2】:

    尝试内置函数 zip 和列表理解:

    z = [i*j for i,j in zip(x,y)]
    

    【讨论】:

      【解决方案3】:

      在这里你有不同的选择:

      >>> x=[1, 4, 0 ,3]
      >>> y=[2, 1, 9 ,4]
      >>> import operator
      >>> list(map(operator.mul, x, y))
      [2, 4, 0, 12]
      

      【讨论】:

        【解决方案4】:

        您可以使用.zip() 来完成此操作

        使用列表推导:

        [x*y for x,y in zip(list_x,list_y)]
        

        没有列表理解:

        for x,y in zip(list_x,list_y):
            print(x*y)
        

        【讨论】:

          【解决方案5】:

          两个数组的乘法只有在两个数组的长度相等时才可能。

          试试这个代码!

          代码:

          x=[1, 4, 0 ,3]
          y=[2, 1, 9 ,4]
          z= []
          if (len(x)==len(y)):
              for i in range(0,len(x)):
                  z.append(x[i]*y[i])
              print(z)
          else:
              print("Array are not equal in size.... Multiplication is not possible")
          

          输出:

          [2, 4, 0, 12]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-02-02
            • 1970-01-01
            • 1970-01-01
            • 2019-10-24
            相关资源
            最近更新 更多