我不能使用Numpy或任何其他库函数,因为这是一个我必须要做的问题,我必须定义我自己的方式。在
我正在编写一个函数,它以两个列表(二维)作为参数。该函数应计算两个列表的元素乘积,并将它们存储在第三个列表中,然后从函数返回此结果列表。 输入列表示例如下:
[[2,3,5,6,7],[5,2,9,3,7]]
该函数将打印以下列表:
[[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)
您可以^{} 在a列表理解中^{} 两个列表,然后进一步^{} 生成子列表,然后将项目相乘:
如果列表/子列表没有相同数量的元素,^{} 可用于生成填充值,如较小列表的空子列表,或较短子列表的0:
^{pr2}$您可以将内部
fillvalue
从0更改为1,以按原样返回较长子列表中的元素,而不是同构的0。在参考:
List comprehensions
下面是一个函数,它可以处理任何类型的iterable,嵌套到任何级别(任何数量的维度,而不仅仅是2个维度):
此函数以递归方式工作。对于列表中的每个元素,它检查元素是否可读取。如果是,则输出元素是一个包含iterables的元素乘法的列表。如果不是,则返回数字的乘积。在
此解决方案适用于混合嵌套类型。这里的两个假设是所有嵌套级别的大小都是相同的,并且一个iterable中的一个数字(相对于嵌套的iterable)在另一个iterable中总是一个数字。在
事实上,这个代码片段可以扩展为将任何n元函数应用于任何n个iterable:
^{pr2}$要进行乘法,您可以使用
operator.mul
:生产
在Python中,通常最好直接循环列表中的项,而不是使用索引间接循环。由于避免了繁琐的索引运算,因此它使代码更易于阅读,同时也更高效。在
下面是如何使用传统的} 函数同时迭代两个(或多个)列表。在
for
循环来解决您的问题。我们使用内置的^{输出
^{pr2}$我们可以使用list comprehensions使代码更加紧凑。一开始读起来可能很难,但你会习惯于通过练习列出理解。在
相关问题 更多 >
编程相关推荐