gpt4 book ai didi

python - 两个二维列表的逐元素乘积

转载 作者:太空宇宙 更新时间:2023-11-03 12:56:23 25 4
gpt4 key购买 nike

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

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

列表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 list comprehension 中的两个列表,然后进一步 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 以按原样返回较长子列表中的元素,而不是同类 0。


引用:

List comprehensions

关于python - 两个二维列表的逐元素乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40155503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com