0

I have two arrays that need to be combined into a single array by adding the together the values from each array.

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]

x = np.sum(a, b)

the result I want is:

x = [2, 4, 6, 8, 10]

then to be able to calculate the average of each value to get results:

x = [1, 2, 3, 4, 5] 

When I run that, it returns the error

TypeError: 'list' object cannot be interpreted as an integer
1

2 Answers 2

2

sum takes the sum of a sequence of objects. For instance, sum(a) would yield the value 15. You gave it two lists.

Since you want to add two arrays, you need to convert the lists to numpy arrays first; then you can add them as a numpy vector addition.

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> b = np.array([1, 2, 3, 4, 5])
>>> a+b
array([ 2,  4,  6,  8, 10])
>>> (a+b)/2
array([ 1.,  2.,  3.,  4.,  5.])
Sign up to request clarification or add additional context in comments.

Comments

1

Use some good ole list comprehension. The zip function will also help us in this case.

result = [x+y for x, y in zip(a,b)]

Zip joins each element of x to an element of y at the same index and stops when one list runs out. List comprehension takes each element in the newly created list and adds the two that are next to each other together.

So it looks like this expanded:

for n,z in zip(x,y):
    x.append(n+z)

example:

> a = b = [1,2,3,4,5]
> result = [x+y for x, y in zip(a,b)]
> result
[2, 4, 6, 8, 10]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.