2个列表之间的相乘 [英] Multiplication between 2 lists

查看:78
本文介绍了2个列表之间的相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个列表

a=[[2,3,5],[3,6,2],[1,3,2]]
b=[4,2,1]

我希望输出为:

c=[[8,12,20],[6,12,4],[1,3,2]]

目前我正在使用以下代码,但是它的问题是计算时间非常长,因为列表中的值数量很大.列表的第一个列表有1000个列表,其中每个列表有10000个值,并且第二个列表有1000个值,因此计算时间是一个问题.我想要一个新的想法,其中计算时间更少.当前代码为:

At present i am using the following code but its problem is that the computation time is very high as the number of values in my list are very large.The first list of list has 1000 list in which each list has 10000 values and the second list has 1000 values.Therefore the computation time is a problem.I want a new idea in which computation time is less.The present code is:

a=[[2,3,5],[3,6,2],[1,3,2]]
b=[4,2,1]
c=[]
s=0
for i in b:
    c1=[]
    t=0
    s=s+1
    for j in a:
        t=t+1
        for k in j:
            if t==s:
                m=i*k
                c1.append(m)
    c.append(c1)
print(c)

推荐答案

您可以使用numpy:

You can use numpy :

>>> import numpy as np
>>> a=np.array([[2,3,5],[3,6,2],[1,3,2]])
>>> b=np.array([4,2,1])

>>> a*np.vstack(b)
array([[ 8, 12, 20],
       [ 6, 12,  4],
       [ 1,  3,  2]])

或者像@ csunday95建议的那样,它是一种更优化的方式,您可以使用转置而不是vstack:

Or as @csunday95 suggested as a more optimized way you can use transpose instead of vstack :

>>> (a.T*b).T 
array([[ 8, 12, 20],
       [ 6, 12,  4],
       [ 1,  3,  2]])

这篇关于2个列表之间的相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆