【问题标题】:Multiply two lists but multiply each number in the first list by all numbers in the second list in python将两个列表相乘,但将第一个列表中的每个数字乘以 python 中第二个列表中的所有数字
【发布时间】:2022-01-07 00:05:00
【问题描述】:

我有两个列表,我想将第一个列表中的每个数字乘以第二个列表中的所有数字

[1,2]x[1,2,3]

我希望我的结果是这样的[(1x1)+(1x2)+(1x3),(2x1)+(2x2)+(2x3)]

【问题讨论】:

  • 那么你有什么尝试?显示您的代码minimal reproducible example 并说明您需要帮助的具体问题。
  • 当心,Python 列表和 numpy 数组是非常不同的动物,解决方案也会大不相同。你必须准确地说你想做什么。

标签: python list numpy


【解决方案1】:

正如 cmets 指出的那样,纯 Python 解决方案与 numpy 解决方案将大不相同。

Pyhton

这里可以直接使用嵌套循环或列表推导:

list1 = [1, 2]
list2 = [1, 2, 3]

lst_output = []
for i in list1:
    for j in list2:
        lst_output .append(i*j)

#equivalent alternative
lst_output = [i*j for i in list1 for j in list2]

Numpy

numpy 也有很多方法可以解决这个问题。这是一个例子:

arr1 = np.array([1, 2])
arr2 = np.array([1, 2, 3])

xx, yy = np.meshgrid(arr1, arr2)

arr_output = xx * yy 

# optionally (to get a 1d array)
arr_output_flat = arr_output.flatten() 

编辑:再次阅读您的问题,我注意到您声明您实际上希望输出为 2 个总和(3 个产品)。我建议你更准确地说出你想要的和你尝试过的。但是为了提供这些,您可以对上面的列表或数组执行以下操作:

# Pure Python
lst_output = [sum(i*j for j in list2) for i in list1]

# Numpy
xx, yy = np.meshgrid(arr1, arr2)
arr_output = np.sum(xx * yy, axis=0)

【讨论】:

    【解决方案2】:

    numpy

    ​​>
    a = np.array([1,2])
    b = np.array([1,2,3])
    
    c = (a[:,None]*b).sum(1)
    

    输出:array([ 6, 12])

    蟒蛇

    a = [1,2]
    b = [1,2,3]
    
    c = [sum(x*y for y in b) for x in a]
    

    输出:[6, 12]


    旧答案(每个元素的产品)

    numpy
    a = np.array([1,2])
    b = np.array([1,2,3])
    c = (a[:,None]*b).ravel()
    

    输出:array([1, 2, 3, 2, 4, 6])

    蟒蛇
    a = [1,2]
    b = [1,2,3]
    
    c = [x*y for x in a for y in b]
    
    ## OR
    from itertools import product
    c = [x*y for x,y in product(a,b)]
    

    输出:[1, 2, 3, 2, 4, 6]

    【讨论】:

      【解决方案3】:

      使用 numpy 的另一种方式(您可以扩展到两个列表之间的许多其他函数):

      a = [1,2]
      b = [1,2,3]
      np.multiply.outer(a,b).ravel()
      #array([1, 2, 3, 2, 4, 6])
      

      【讨论】:

        【解决方案4】:
        def multiplyLists(list1: list, list2:list) -> list:
            toReturn = []
            for i in list1:
                temp_sum = 0
                for j in list2:
                    temp_sum += i * j
                toReturn.append(temp_sum)
            return toReturn
        

        【讨论】:

          猜你喜欢
          • 2012-09-19
          • 1970-01-01
          • 1970-01-01
          • 2022-12-13
          • 2016-05-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多