Thanos Smar Thanos Smar - 6 months ago 9
Python Question

How to append a 3d list and print its contents?

I want to create a list that has N lists, each of which will be filled with values that will be computed like this:

for i in range(R): for j in range(R): b.append(a[i]-a[j])


All the differences between i and j with step 2

I have this code:

b = []
for i in range(N):
b.append([])
for j in range(R):
b[i].append([])
for k in range(R,2):
b[i][j].append(a[j]-a[k])
print b


Which gives:

[[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]]

Answer

I'm not sure what N, R and a are, but I think the problem is in range(R,2). It should be range(0,R,2). Right now your last for loop doesn't do anything. I'm also not sure what 'a' is doing there.

N = 5
R = 4

b = []
for i in range(N):
    b.append([])
    for j in range(R):
        b[i].append([])
        for k in range(0,R,2):
            b[i][j].append(j - k)
print b

The code above returns the following:

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

It's N lists of R lists of R/2 values. Is this what you're after?