如何将嵌套列表与列表相乘?

问题描述 投票:0回答:2

我有:

dataA=[[1,2,3],[1,2,5]]
dataB=[1,2]

我想将索引[0]数据A与索引[0]数据B相乘,并将索引[1]数据A与索引[1]数据B相乘,如何操作。

我尝试过,但结果与预期不符

dataA=[[1,2,3],[1,2,5]]
dataB=[1,2]

tmp=[]
for a in dataA:
    tampung = []
    for b in a:
        cou=0
        hasil = b*dataB[cou]
        tampung.append(hasil)
        cou+=1
    tmp.append(tampung)
print(tmp)

输出:[[1, 2, 3], [1, 2, 5]]预期输出:[[1,2,3],[2,4,10]]

请帮助

python-3.x list arraylist nested-lists multiplying
2个回答
0
投票

列表表达式在Python中非常出色。

result = [[x*y for y in l]for x, l in zip(dataB, dataA)]

这与之相同:

result = []
for x, l in zip(dataB, dataA):
    temp = []
    for y in l:
        temp.append(x * y)
    result.append(temp)
result
## [[1, 2, 3], [2, 4, 10]]

0
投票

如果您正在处理数字,请考虑使用numpy,因为它将使您的操作更加容易。

dataA = [[1,2,3],[1,2,5]]
dataB = [1,2]

# map list to array
dataA = np.asarray(dataA) 
dataB = np.asarray(dataB) 

# dataA = array([[1, 2, 3], [1, 2, 5]]) 
# 2 x 3 array

# dataB = array([1, 2])
# 1 x 2 array

dataC_1 = dataA[0] * dataB[0] #multiply first row of dataA w/ first row of dataB
dataC_2 = dataA[1] * dataB[1] #multiply second row of dataA w/ second row of dataB

# dataC_1 = array([1, 2, 3])
# dataC_2 = array([2, 4, 10])


这些数组始终可以通过将其传递到List()中来强制返回到列表中

正如其他贡献者所说,请查看numpy库!

© www.soinside.com 2019 - 2024. All rights reserved.