繁体   English   中英

两个二维列表的元素乘积

[英]Element-wise product of two 2-D lists

我不能使用Numpy或任何其他库函数,因为这是我必须要做的一个问题,我必须定义自己的方式。

我正在编写一个函数,它将两个列表(2维)作为参数。 该函数应计算两个列表的元素乘积并将它们存储在第三个列表中,并从函数返回该结果列表。 输入列表的示例是:

列表1:

[[2,3,5,6,7],[5,2,9,3,7]]  

列表2:

[[5,2,9,3,7],[1,3,5,2,2]]

该函数打印以下列表:

[[10, 6, 45, 18, 49], [5, 6, 45, 6, 14]] 

那是2*5=10 3*2=6 5*9=45 ......依此类推。

这是我的下面的代码,但它只适用于里面有2个列表(元素)的列表,就像上面的例子一样,并且完全可以正常工作,但我想要的是编辑我的代码,这样无论有多少个列表(元素)存在于二维列表中,它应该在一个新的二维列表中打印出它的元素产品,例如它也应该适用于

[[5,2,9,3,7],[1,3,5,2,2],[1,3,5,2,2]]

要么

[[5,2,9,3,7],[1,3,5,2,2],[1,3,5,2,2],[5,2,9,3,7]]

或整个列表中的任意数量的列表。

def ElementwiseProduct(l,l2):
    i=0
    newlist=[] #create empty list to put prouct of elements in later
    newlist2=[]
    newlist3=[] #empty list to put both new lists which will have proudcts in them
    while i==0:
        a=0
        while a<len(l[i]):
            prod=l[i][a]*l2[i][a] #corresponding product of lists elements
            newlist.append(prod) #adding the products to new list
            a+=1
        i+=1
    while i==1:
        a=0
        while a<len(l[i]):
            prod=l[i][a]*l2[i][a] #corresponding product of lists elements
            newlist2.append(prod) #adding the products to new list
            a+=1
        i+=1
    newlist3.append(newlist)
    newlist3.append(newlist2)
    print newlist3

#2 dimensional list example
list1=[[2,3,5,6,7],[5,2,9,3,7]] 
list2=[[5,2,9,3,7],[1,3,5,2,2]]  
ElementwiseProduct(list1,list2)

您可以zip这两个列表列表中的理解 ,则进一步zip所产生的子表 ,然后最后乘以项目:

list2 = [[5,2,9,3,7],[1,3,5,2,2]]
list1 = [[2,3,5,6,7],[5,2,9,3,7]]

result = [[a*b for a, b in zip(i, j)] for i, j in zip(list1, list2)]
print(result)
# [[10, 6, 45, 18, 49], [5, 6, 45, 6, 14]]

如果列表 / 子列表没有相同数量的元素,则itertools.izip_longest可用于生成填充值,例如较小列表的空子列表,或较短子列表的0:

from itertools import izip_longest

list1 = [[2,3,5,6]]
list2 = [[5,2,9,3,7],[1,3,5,2,2]]
result = [[a*b for a, b in izip_longest(i, j, fillvalue=0)] 
               for i, j in izip_longest(list1, list2, fillvalue=[])]
print(result)
# [[10, 6, 45, 18, 0], [0, 0, 0, 0, 0]]

您可以将内部fillvalue从0更改为1,以按fillvalue返回较长子列表中的元素,而不是同类0。


参考

列表理解

这是一个可以处理任何类型的iterable的函数,嵌套到任何级别(任意数量的维度,而不仅仅是2):

def elementwiseProd(iterA, iterB):
    def multiply(a, b):
        try:
            iter(a)
        except TypeError:
            # You have a number
            return a * b
        return elementwiseProd(a, b)
    return [multiply(*pair) for pair in zip(iterA, iterB)]

此函数递归工作。 对于列表中的每个元素,它检查元素是否可迭代。 如果是,则输出元素是包含迭代的元素乘法的列表。 如果不是,则返回数字的乘积。

此解决方案适用于混合嵌套类型。 这里做出的一些假设是,所有嵌套级别都是相同的大小,并且一个迭代中的数字元素(相对于嵌套的可迭代)始终是另一个中的数字。

事实上,这个代码片段可以扩展为将任何n-ary函数应用于任何n个迭代:

def elementwiseApply(op, *iters):
    def apply(op, *items):
        try:
            iter(items[0])
        except TypeError:
            return op(*items)
        return elementwiseApply(op, *items)
    return [apply(op, *items) for items in zip(*iters)]

要进行乘法运算,您可以使用operator.mul

from operator import mul
list1=[[2,3,5,6,7], [5,2,9,3,7]] 
list2=[[5,2,9,3,7], [1,3,5,2,2]]
elementwiseApply(mul, list1, list2)

产生

[[10, 6, 45, 18, 49], [5, 6, 45, 6, 14]]

在Python中,通常最好直接循环遍历列表中的项,而不是使用索引间接循环。 它使代码更容易阅读,也更有效,因为它避免了繁琐的索引算法。

以下是使用传统for循环解决问题的方法。 我们使用内置的zip函数同时迭代两个(或更多)列表。

def elementwise_product(list1,list2):
    result = []
    for seq1, seq2 in zip(list1,list2):
        prods = []
        for u, v in zip(seq1, seq2):
            prods.append(u * v)
        result.append(prods)
    return result

list1=[[2,3,5,6,7], [5,2,9,3,7]] 
list2=[[5,2,9,3,7], [1,3,5,2,2]]

print(elementwise_product(list1,list2))

产量

[[10, 6, 45, 18, 49], [5, 6, 45, 6, 14]]

我们可以使用列表推导来使代码更紧凑。 一开始看起来可能看起来更难,但你会习惯用练习列出理解。

def elementwise_product(list1,list2):
    return [[u*v for u, v in zip(seq1, seq2)] 
        for seq1, seq2 in zip(list1,list2)]

你可以使用numpy数组。 它们是您最好的选择,因为它们在C背景上运行,因此计算速度更快

首先,安装numpy。 点击您的终端(如果您在窗口中,则为CMD),键入

pip install numpy

或者,如果在Linux中, sudo pip install numpy

然后,继续编写代码

import numpy as np

list1=np.array([[2,3,5,6,7],[5,2,9,3,7]]) #2 dimensional list example
list2=np.array([[5,2,9,3,7],[1,3,5,2,2]])

prod = np.multiply(list1,list2)
# or simply, as suggested by Mad Physicist,
prod = list1*list2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM