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

how to multiply nested list with list?

我有:

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

我想将索引[0] dataA乘以索引[0] dataB,索引[1] dataA乘以索引[1] dataB,如何做。

我试过了,结果不符合预期

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.

中非常棒
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]]

如果您正在处理数字,请考虑使用 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 库!