frsnmk
frsnmk

Reputation: 137

how to multiply nested list with list?

i have:

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

I want to multiply index [0] dataA with index [0] dataB, and index [1] dataA with index [1] dataB, how to do it.

I tried it, but the results didn't match expectations

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)

output : [[1, 2, 3], [1, 2, 5]] expected output : [[1,2,3],[2,4,10]]

Please help

Upvotes: 1

Views: 2079

Answers (2)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

List-expression are sth wonderful in Python.

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

This does the same like:

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]]

Upvotes: 3

r4bb1t
r4bb1t

Reputation: 1165

If you are working with numbers consider using numpy as it will make your operations much easier.

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])


These arrays can always be cast back into lists by passing them into List()

As other contributors have said, please look into the numpy library!

Upvotes: 0

Related Questions