简体   繁体   中英

How to Iterate over a list of numpy arrays in Python 3

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]]

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())

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM