简体   繁体   中英

How to sum every couple of consecutive elements in an array?

I have an array of size (1,10) :

A = [1 2 3 4 5 6 7 8 9 10]

Now I want to compute a new array with size (1,5) as:

B = [3 7 11 15 19]

Which is constructed by:

3 = 1 + 2
7 = 3 + 4
...
19 = 9 + 10

How can I implement it in Python?

You can index the array at every nth element by the syntax [::n]

a = np.arange(1,11)
a[::2] + a[1::2]
array([ 3,  7, 11, 15, 19])

To generalize the question:

You have an array A with size 2n and you want to get array B with size n so each element in B is the sum of two elements from A taken in sequential order.

The easiest solution is to create a for loop with n iterations and do the summation for the corresponding elements.

A = np.array([1,2,3,4,5,6,7,8,9,10])
B = np.zeros(shape=(5), dtype=int)

for i in range(len(A) // 2):
  B[i]=(A[2*i] + A[2*i+1])

print(B)

You can also use list comprehension:

A = np.array([1,2,3,4,5,6,7,8,9,10])

B = np.array([A[2*i]+A[2*i+1] for i in range(len(A)//2)])

print(B)

A.shape is (10,), not (1,10).

 A.reshape(-1,2)

makes a (5,2) array

  A.reshape(-1,2).sum(axis=1)

sums across columns

total = sum(arraylist)
print(arraylist)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM