-1

That this answer to Convert numpy ndarray to tuple of tuples in optimize method doens't offer anything more than tuple(tuple(i) for i in a[:,0,:]) suggests this doesn't exist, but I am looking for something like a .totuple() method similar to numpy's .tolist() in that you don't need to know the number of dimensions beforehand to generate a tuple of tuples of tuples...

For my needs this would apply to a float or integer numerical array only.

uhoh
  • 3,392
  • 5
  • 34
  • 89
  • 1
    ``numpy` does not have hidden methods! For most purposes `tolists` is sufficient, and faster than any iteration on an array. It also takes the conversion all the way down, producing python end values (i.e. `int` instead of `np.int64`). – hpaulj Jul 13 '21 at 12:52
  • @hpaulj thanks, I have a hunch that JelleWestra's answer is as good as it's going to get. I'll see if I can make `.tolist()` work for me. If there's no `totupple()` there must be some reason for that. Is there a PEP for [I Do Not Want What I Haven't Got](https://en.wikipedia.org/wiki/I_Do_Not_Want_What_I_Haven%27t_Got)? :-) – uhoh Jul 13 '21 at 13:03

1 Answers1

1

You can make use of a recursive function which converts to a tuple independent of the number of dimensions:

def totuple(a):
    try:
        return tuple(totuple(i) for i in a)
    except TypeError:
        return a

Found in this answer: Convert numpy array to tuple

Jelle Westra
  • 411
  • 3
  • 7
  • Interesting! I will give it a try. I was hoping for "something like a `.totuple()` *method* similar to numpy's `.tolist()`" so I wouldn't have to rewrite it every time I need it, but it may not exist. – uhoh Jul 13 '21 at 12:08
  • 1
    @uhoh As far as I'm aware, there doesn't exist such a method or function in numpy unfortunately. – Jelle Westra Jul 13 '21 at 12:13
  • Applying this function to the `tolist` result is probably faster. – hpaulj Jul 13 '21 at 12:54