For loop arrays operation

Advertisements

I would like to write these expressions in a nicer way, with a for loop.
I have to do it 4 times for u1, u2, v1 and v2 and store these 3 arrays each time.

delta_u1_up_down = [u1[2] - u1[1], u1[4] - u1[3], u1[6] - u1[5],
                        u1[8] - u1[7], u1[10] - u1[9], u1[12] - u1[11], u1[14] - u1[13],
                        u1[16] - u1[15], u1[18] - u1[17]]

delta_u1_first = [u1[1] - u1[17], u1[3] - u1[17], u1[5] - u1[17], u1[7] - u1[17],
                      u1[9] - u1[17], u1[11] - u1[17], u1[13] - u1[17], u1[15] - u1[17],
                      u1[2] - u1[18], u1[4] - u1[18], u1[6] - u1[18], u1[8] - u1[18],
                      u1[10] - u1[18], u1[12] - u1[18], u1[14] - u1[18],
                      u1[16] - u1[18]]

delta_u1_previous = [u1[1] - u1[3], u1[3] - u1[5], u1[5] - u1[7], u1[7] - u1[9],
                         u1[9] - u1[11], u1[11] - u1[13], u1[13] - u1[15],
                         u1[15] - u1[17], u1[2] - u1[4], u1[4] - u1[6], u1[6] - u1[8],
                         u1[8] - u1[10], u1[10] - u1[12], u1[12] - u1[14],
                         u1[14] - u1[16], u1[16] - u1[18]]

Can someone please help me? The order is always the same.

>Solution :

Check out range(start, stop, step):

delta_u1_up_down  = [u1[i] - u1[i-1] for i in range(2, 19, 2)]
delta_u1_first    = [u1[i] - u1[17] for i in range(1, 17, 2)] +
                    [u1[i] - u1[18] for i in range(2, 18, 2)]
delta_u1_previous = [u1[i] - u1[i+2] for i in range(1, 17, 2)] +
                    [u1[i] - u1[i+2] for i in range(2, 18, 2)]

Leave a Reply Cancel reply