Tapasya.A
Tapasya.A

Reputation: 87

Appending values at correct position

For the following declared lists:

a =[[array([0, 1, 2, 3, 4])], [array([0, 1, 2]), array([3, 4])], [array([0, 1]), array([2, 3]), array([4])]]
t= [[[]], [[], []], [[], [], []]]

I wrote a code as shown below. (one can easily see that the 't' has same dimensions as that of 'a' upto second order)

 import numpy as np
 for i in range(3):
    for j in range(len(a[i])):
       for k in range(len(a[i][j])-1):
           p = k*(a[i][j][k+1]-a[i][j][k])
           print(p)
       t[i][j].append(p)
       print(t)

This works well with the output of 'p' which is the following:

0
1
2
3
0
1
0
0
0

However the output value of t is unexpected. I was actually expecting the following form of 't' where the values of 'p' goes to their corresponding sublist.

t=[[[0,1,2,3]],[[0,1],[0]],[[0],[0],[0]]]

I don't understand the flaw in my code.

What could be possible way to get the desired outcome of 't'? Please help. Thank you.

Upvotes: 1

Views: 62

Answers (1)

Nic
Nic

Reputation: 3507

bad indent for t[i][j].append(p)? Althought it's hard to understand what you want to achieve, but below results looks very similar to your expect.

for i in range(3):
   for j in range(len(a[i])):
      for k in range(len(a[i][j])-1):
          p = k*(a[i][j][k+1]-a[i][j][k])
          #print(p)
          t[i][j].append(p)
print(t)

prints:

[[[0, 1, 2, 3]], [[0, 1], [0]], [[0], [0], []]]

Upvotes: 1

Related Questions