Reputation: 31
For example, I have these two arrays:
a = [1,3,5,7,9] b = [2,4,6]
I want to add the sum of products multiplying each value of array a by every value of array b. Ultimately resulting in a new array that would look like.
[12, 36, 60, 84, 108]
I get as far as:
a = [1,3,5,7,9]
b = [2,4,6]
ab = []
for i in range(len(a)):
for j in range(len(b)):
ab.append(a[i]*b[j])
print(ab)
But unsure how to add the products.
Thanks for the advice!
Upvotes: 3
Views: 185
Reputation: 1761
Obligatory numpy solution
import numpy as np
a = np.array([1,3,5,7,9])
b = np.array([2,4,6])
np.sum(a[:,None]*b[None,:], axis=1)
Output
array([ 12, 36, 60, 84, 108])
Upvotes: 0
Reputation: 71560
Why not this then:
[i*sum(b) for i in a]
Demo:
a = [1,3,5,7,9]
b = [2,4,6]
print([i*sum(b) for i in a])
Output:
[12, 36, 60, 84, 108]
Upvotes: 2
Reputation: 1471
Did you mean to multiply each element in a with sum(b)? This code will do it for you.
a = [1,3,5,7,9]
b = [2,4,6]
b_sum = sum(b)
ab = [x * b_sum for x in a]
Upvotes: 1