Question

I am new to cython and I am just looking for an easy way of casting a numpy array to a tuple that can then be added to and/or looked up in a dictionary.

In CPython, I can use PyTuple_New and iterate over the values of the array (adding each one to the tuple as though I were appending them to a list).

Cython does not seem to come with the usual CPython functions. How might I turn an array:

array([1,2,3])

into a tuple:

(1, 2, 3)
Was it helpful?

Solution

Cython is a superset of Python so any valid Python code is a valid Cython code. In this case, if you have a NumPy array, just passing it to a tuple class constructor should work just fine (just as you would do in regular Python).

a = np.array([1, 2, 3])
t = tuple(a)

Cython will take care of converting these constructs to appropriate C function calls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top