0

I'm having some trouble in Python as beginner. Let me use some example and let's consider the foloowing data :

data = [[1, 7],
        [2, 8],
        [3, 9],
        [4, 10],
        [5, 11],
        [6, 12],
        [13, 14],
        [15, 16]]

I want as output :

B       = [[1+3+5+13, 7+9+11+14],
          [2+4+6+15, 8+10+12+16]]

To do it, i already tried to slice the data array into smaller arrays (2x2), but i can't find a way to make it works. I think that if i can find a way to make this small program works, I will be able to work with bigger files of data.

So that's my actual code :

A= {}
m=2
A=[data[idx: idx + m] for idx in range(0, len(data), m)]
B=[]
for a in range(1,2) :
    for l in range(2):
        B.append([])
        for c in range(2):
            B[l].append(A[a][l][c])
            print('B = ' + str(B))
print('end')

Thank you for your time.

3 Answers 3

1

The four sums you want can be calculated efficiently like this:

import numpy as np
arr = np.array(data)

w = arr[0::2,0] # array([ 1,  3,  5, 13])
x = arr[0::2,1] # array([ 7,  9, 11, 14])
y = arr[1::2,0] # array([ 2,  4,  6, 15])
z = arr[1::2,1] # array([ 8, 10, 12, 16])

B = [[w.sum(), x.sum()], [y.sum(), z.sum()]]

arr[1::2,0] means "Starting from row 1, take every second row, then take column 0."

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, but i'm looking for some solution with loops, because my data-array can be made of way more 2x2 arrays inside. So i can't know how many variables (names w, x, y, z) i need
@NycoElm: If you want a more general solution please post an alternative input and output example in the question. Or, just have a go at writing the loop yourself using the above building blocks.
Yeah sorry i should have present a way more generic solution... But I was thinking if i can solve this problem i would be able to extend to other application. I'll try with loops, thanks !
0
def slice_array(raw_data):
    ret = [[0,0],
          [0,0]]
    for d in range(len(raw_data)):
        if d % 2 == 0:
           ret [0][0] += raw_data[d][0]
           ret [0][1] += raw_data[d][1] 
        if d % 2 == 1:
           ret [1][0] += raw_data[d][0]
           ret [1][1] += raw_data[d][1] 
    return ret

This should work. Just give the array you want to slice as input.

Comments

0

This code should also work :

X1 = [x[0] for x in data]
X2 = [x[1] for x in data]

B = [ [sum(X1[0::2]), sum(X2[0::2])], 
      [sum(X1[1::2]), sum(X2[1::2])]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.