将numpy数组转换为元组 [英] Convert numpy array to tuple

查看:157
本文介绍了将numpy数组转换为元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这是与通常的元组到数组的转换相反的要求.

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

我必须将参数传递给(包装的c ++)函数作为嵌套元组.例如,以下作品

I have to pass an argument to a (wrapped c++) function as a nested tuple. For example, the following works

X = MyFunction( ((2,2),(2,-2)) )

而以下

X = MyFunction( numpy.array(((2,2),(2,-2))) )
X = MyFunction( [[2,2],[2,-2]] )

不幸的是,我想使用的参数以numpy数组的形式出现.对于某些N,该阵列的尺寸始终为2xN,这可能会很大.

Unfortunately, the argument I would like to use comes to me as a numpy array. That array always has dimensions 2xN for some N, which may be quite large.

是否有一种简单的方法可以将其转换为元组?我知道我可以循环遍历,创建一个新的元组,但是如果numpy数组提供了一些不错的访问方式,则希望使用它.

Is there an easy way to convert that to a tuple? I know that I could just loop through, creating a new tuple, but would prefer if there's some nice access the numpy array provides.

如果不可能如我所愿地做到这一点,那么通过循环执行此操作的最漂亮的方法是什么?

If it's not possible to do this as nicely as I hope, what's the prettiest way to do it by looping, or whatever?

推荐答案

>>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2))

这篇关于将numpy数组转换为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆