【问题标题】:How do I multiply lists together using a function?如何使用函数将列表相乘?
【发布时间】:2020-11-27 13:09:31
【问题描述】:

如何在 python 中使用函数将列表相乘?这就是我所拥有的:

    list = [1, 2, 3, 4]
    def list_multiplication(list, value):
         mylist = []
         for item in list:
              for place in value:
               mylist.append(item*value)
    return mylist

所以我想用它来乘以 list*list (1*1, 2*2, 3*3, 4*4)

所以输出将是 1、4、9 和 16。我将如何在第二个列表可以是任何东西的 python 中执行此操作? 谢谢

【问题讨论】:

  • 原代码的问题在于,它为外层列表(列表)的每次迭代迭代了内层列表(值)一次。虽然下面有很多方法,但基本的关键是“逐步迭代两个列表”。

标签: python list multiplication


【解决方案1】:

我最喜欢的方式是将mul 运算符映射到两个列表:

from operator import mul

mul(2, 5)
#>>> 10

mul(3, 6)
#>>> 18

map(mul, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
#>>> <map object at 0x7fc424916f50>

map,至少在 Python 3 中,返回一个生成器。因此,如果您想要一个列表,您应该将其转换为一个:

list(map(mul, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10]))
#>>> [6, 14, 24, 36, 50]

但到那时,对zip'd 列表使用列表推导可能更有意义。

[a*b for a, b in zip([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])]
#>>> [6, 14, 24, 36, 50]

为了解释最后一个,zip([a,b,c], [x,y,z]) 给出(生成器)[(a,x),(b,y),(c,z)]

for a, b in 将每个(m,n) 对“解包”为变量ab,然后a*b 将它们相乘。

【讨论】:

    【解决方案2】:

    您可以使用列表推导:

    >>> t = [1, 2, 3, 4]
    >>> [i**2 for i in t]
    [1, 4, 9, 16]
    

    注意1*1, 2*2, etc 与数字平方相同。


    如果您需要将两个列表相乘,请考虑zip()

    >>> L1 = [1, 2, 3, 4]
    >>> L2 = [1, 2, 3, 4]
    >>> [i*j for i, j in zip(L1, L2)]
    [1, 4, 9, 16]
    

    【讨论】:

    • 我知道,但是我将如何处理另一个列表?那么我上面提供的列表乘以另一个列表?假设我将上面的列表乘以 list2 = [2,5,6,3]
    【解决方案3】:

    如果您有两个相同长度的列表AB,最简单的方法是zip

    >>> A = [1, 2, 3, 4]
    >>> B = [5, 6, 7, 8]
    >>> [a*b for a, b in zip(A, B)]
    [5, 12, 21, 32]
    

    单独查看zip 以了解其工作原理:

    >>> zip(A, B)
    [(1, 5), (2, 6), (3, 7), (4, 8)]
    

    【讨论】:

    • 没有 zip 有什么办法吗?这很好用,但我只是好奇。谢谢
    • 当然,有无数种方法可以做到这一点;-) 例如,[A[i]*B[i] for i in range(len(A))]
    • @user2817437 你没看到我的帖子吗?我在你问之前 25 分钟介绍了一条路。另请参阅izip's equivalent implementation from the docs,了解无需索引即可手动执行此操作的方法。
    • @TimPeters 你能详细说明一下另一个例子吗?它如何适应函数和 for 循环?
    • @user2817437,对不起,我猜不出你在问什么。如何编辑您的问题,准确地总结您正在寻找的内容:输入、输出以及您尝试过但仍无法获得您想要的内容。
    【解决方案4】:

    zip() 会这样做:

    [a*b for a,b in zip(lista,listb)]
    

    【讨论】:

      【解决方案5】:

      zip 可能是要走的路,正如其他答案所建议的那样。也就是说,这是另一种初学者方法。

      # create data
      size = 20
      a = [i+1 for i in range(size)]
      b = [val*2 for val in a]
      
      a
      >> [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20] 
      b
      >> [ 2  4  6  8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40] 
      
      def multiply_list_elems(list_one, list_two):
          """ non-efficient method """
          res = [] # initialize empty list to append results
          if len(a) == len(b): # check that both lists have same number of elems (and idxs)
              print("\n list one: \n", list_one, "\n list two: \n", list_two, "\n")
              for idx in range(len(a)): # for each chronological element of a
                  res.append(a[idx] * b[idx]) # multiply the ith a and ith b for all i
          return res
      
      def efficient_multiplier(list_one, list_two):
          """ efficient method """
          return [a[idx] * b[idx] for idx in range(len(a)) if len(a) == len(b)]
      
      print(multiply_list_elems(a, b))
      print(efficient_multiplier(a, b))
      

      两者都给出:

      >> [2, 8, 18, 32, 50, 72, 98, 128, 162, 200, 242, 288, 338, 392, 450, 512, 578, 648, 722, 800]
      

      另一种方法是使用 numpy,as suggested here

      【讨论】:

        【解决方案6】:

        为此使用 numpy。

        >>> import numpy as np
        >>> list = [1,2,3,4]
        >>> np.multiply(list, list)
        array([ 1,  4,  9, 16])
        

        如果你更喜欢 python 列表:

        >>> np.multiply(list, list).tolist()
        [1, 4, 9, 16]
        

        此外,这也适用于标量的元素乘法。

        >>> np.multiply(list, 2)
        array([2, 4, 6, 8])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-29
          • 2018-11-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多