John Cack
John Cack

Reputation: 31

Python - How to create new array of product sums from one array value times all values of another

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

Answers (4)

C. Yduqoli
C. Yduqoli

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

U13-Forward
U13-Forward

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

Blownhither Ma
Blownhither Ma

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

Transhuman
Transhuman

Reputation: 3547

[sum(i*j for j in b) for i in a]
#[12, 36, 60, 84, 108]

Upvotes: 1

Related Questions