Convert numpy array to tuple

后端 未结 5 1567
北海茫月
北海茫月 2020-12-07 11:12

Note: This is asking for the reverse of the usual tuple-to-array conversion.

I have to pass an argument to a (wrapped c++) function as a nested tupl

相关标签:
5条回答
  • 2020-12-07 11:30

    Another option

    tuple([tuple(row) for row in myarray])
    

    If you are passing NumPy arrays to C++ functions, you may also wish to look at using Cython or SWIG.

    0 讨论(0)
  • 2020-12-07 11:32

    If you like long cuts, here is another way tuple(tuple(a_m.tolist()) for a_m in a )

    from numpy import array
    a = array([[1, 2],
               [3, 4]])
    tuple(tuple(a_m.tolist()) for a_m in a )
    

    The output is ((1, 2), (3, 4))

    Note just (tuple(a_m.tolist()) for a_m in a ) will give a generator expresssion. Sort of inspired by @norok2's comment to Greg von Winckel's answer

    0 讨论(0)
  • 2020-12-07 11:34

    I was not satisfied, so I finally used this:

    >>> a=numpy.array([[1,2,3],[4,5,6]])
    >>> a
    array([[1, 2, 3],
           [4, 5, 6]])
    
    >>> tuple(a.reshape(1, -1)[0])
    (1, 2, 3, 4, 5, 6)
    

    I don't know if it's quicker, but it looks more effective ;)

    0 讨论(0)
  • 2020-12-07 11:37
    >>> arr = numpy.array(((2,2),(2,-2)))
    >>> tuple(map(tuple, arr))
    ((2, 2), (2, -2))
    
    0 讨论(0)
  • 2020-12-07 11:42

    Here's a function that'll do it:

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

    And an example:

    >>> array = numpy.array(((2,2),(2,-2)))
    >>> totuple(array)
    ((2, 2), (2, -2))
    
    0 讨论(0)
提交回复
热议问题