由于这是我要完成的问题,所以我不能使用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个列表(元素)的列表,就像上面的示例一样,并且对此完美地运行,但我想编辑我的代码,以便无论2-D列表中有多少个列表(元素),它都应打印出其逐元素乘积在一个新的2-D列表中,例如:
[
[2, 5, 6],
[3, 2, 1],
[5, 9, 8]
]
应该返回:
[
[60, 90, 48],
[
30, 45, 24
]
]
[[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)