I am trying to iterate through a 3-D list in python(not numpy but I am willing to convert to a numpy array if this makes it easier) in such a way that from a list like this:
JavaScript
x
2
1
a = [[[0, 0], [3, 0]], [[1, 0], [4, 0]], [[2, 0], [6, 0]] ]
2
I can get the output
JavaScript
1
8
1
[0,0]
2
[1,0]
3
[2,0]
4
[3,0]
5
[4,0]
6
[6,0]
7
8
I can’t figure out how to make it iterate like this…
My code:
JavaScript
1
5
1
a = [[[0, 0], [0, 0]], [[1, 0], [0, 0]], [[2, 0], [0, 0]] ]
2
for i in range(len(a)):
3
for z in range(len(a[i])):
4
print(a[i][z])
5
I’ve tried different things but can’t seem to get this output.
Advertisement
Answer
I think you want to print the nth sub-sublists consecutively from each sublist. You could unpack and zip a
to get an iterable of tuples, then print each pair in them:
JavaScript
1
5
1
for tpl in zip(*a):
2
for pair in tpl:
3
print(pair)
4
5
Output:
JavaScript
1
7
1
[0, 0]
2
[1, 0]
3
[2, 0]
4
[3, 0]
5
[4, 0]
6
[6, 0]
7