1

I currently have a list of numpy arrays. These arrays contain sets of 2D points. I'd like to iterate over each array in this list as depending on the contents of the array two scenarios can occur. The issue I'm running into is that when I try to iterate over the list like so:

for array in list:

it iterates over entries in the arrays as opposed to iterating over the arrays themselves. For example:

a = [array([[[1, 2]], [[3, 4]]], dtype=int32), array([[[5, 6]], [[7, 8)]]], dtype=int32)]
for array in a:
   print(array)

yields

1
2
3
4
5
6
7
8

when I'm expecting to get

[[1, 2], [3, 4]]
[[5, 6], [7, 8]]
3
  • 1
    Sorry, I'm unable to reproduce. Here's my code and I'm getting the output you expect. import numpy as np a = [np.array([[[1, 2]], [[3, 4]]], dtype=np.int32), np.array([[[5, 6]], [[7, 8]]], dtype=np.int32)] for i in a: print(i) [[[1 2]] [[3 4]]] [[[5 6]] [[7 8]]] Commented Apr 14, 2021 at 20:29
  • 3
    After fixing the syntax error in the example you gave, I cannot reproduce what you describe. Commented Apr 14, 2021 at 20:29
  • As a side note, please don't import names from np, especially if you're going to want to use them for other variables. Writing for array in a: in your sample makes array stop referring to the Numpy type and will mess up subsequent code. Commented Apr 14, 2021 at 20:31

2 Answers 2

2

You can use numpy.squeeze to remove one dimension and use .tolist() to print in the format you want.

a = [array([[[1, 2]], [[3, 4]]], dtype=int32),array([[[5, 6]], [[7, 8]]], dtype=int32)]
for array in a:
  print(squeeze(array).tolist())
Sign up to request clarification or add additional context in comments.

Comments

0

I think you have one too many brackets on each array as needed for your results

a = [array([[1, 2], [3, 4]], dtype=int32), array([[5, 6], [7, 8]], dtype=int32)]
for array in a:
   print(squeeze(array).tolist())

still produces

[[1, 2], [3, 4]]
[[5, 6], [7, 8]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.