0

I have a function from an external package that returns a nested group of NumPy arrays. For example, from IPython:

In [28]: out = Function()

In [29]: out
Out[29]: 
[[array([ 1.,  1.,  0.,  1.,  0.])],
 [array([ 4.,  4.,  5.,  4.,  5.])],
 [array([ 3.,  1.,  0.,  0.,  1.])],
 [array([ 3.,  6.,  1.,  6.,  4.])],
 [array([ 3.,  0.,  1.,  1.,  1.])],
 [array([  3.,  17.,  10.,  25.,  23.])],
 [array([ 0.,  0.,  0.,  0.,  0.])],
 [array([ 0.,  0.,  0.,  0.,  0.])],
 [array([ 0.,  4.,  2.,  5.,  3.])],
 [array([ 0.,  0.,  2.,  2.,  2.])],
 [array([ 0.,  0.,  0.,  0.,  0.])],
 [array([ 0.,  0.,  0.,  0.,  0.])],
 [array([ 0.,  0.,  0.,  0.,  0.])],
 [array([  0.,   1.,   6.,  11.,  15.])]]

I can assign something like:

In [30]: a = out[9]

In [31]: a
Out[31]: [array([ 0.,  0.,  2.,  2.,  2.])]

And then finally:

In [32]: b = a[0]

In [33]: b[-1]
Out[33]: 2.0

To get a specific value that comes out of that array - namely, the last value of the 9th array in the function's output. But I'd really not prefer to make a torrent of variables every time I want to reference something - is there a clean way of referencing a specific interior part of a nested array like this?

2
  • Are you sure this strange list of list of numpy arrays is worth it? You should be able to treat the data as a 2D numpy array for many purposes. Commented Dec 5, 2013 at 21:32
  • @Ophion It's part of an external package. If I was implementing it myself? No. But since I don't want to reimplement the thing from scratch, I'm making due for now. Commented Dec 6, 2013 at 5:44

1 Answer 1

2

That's a strangely shaped object: it's a list of 1-element lists whose element is a 1D numpy array. So we need three indices:

>>> out[9]
[array([ 0.,  0.,  2.,  2.,  2.])]
>>> out[9][0]
array([ 0.,  0.,  2.,  2.,  2.])
>>> out[9][0][-1]
2.0

which will also work if we want to modify it:

>>> out[9][0][-1] *= 100
>>> out[9][0][-1]
200.0
>>> out[9]
[array([   0.,    0.,    2.,    2.,  200.])]
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah - it's an oddly shaped object indeed, and I was having trouble unpacking it in my mind. But the multitude of indices works. Thanks for your help.

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.