【问题标题】:Convert any multi-dimensional numpy array to tuple of tuples of tuples... agnostic of number of dimensions将任何多维 numpy 数组转换为元组元组的元组...与维数无关
【发布时间】:2021-09-22 11:18:01
【问题描述】:

this answer to Convert numpy ndarray to tuple of tuples in optimize method 没有提供比 tuple(tuple(i) for i in a[:,0,:]) 更多的东西,这表明它不存在,但我正在寻找类似于 numpy 的 .tolist().totuple() 方法,因为 你没有t需要事先知道维数才能生成元组的元组...

根据我的需要,这仅适用于浮点数或整数数值数组。

【问题讨论】:

  • ``numpy` 没有隐藏方法!对于大多数目的,tolists 就足够了,而且比数组上的任何迭代都快。它还将转换一路向下,产生 python 最终值(即int 而不是np.int64)。
  • @hpaulj 谢谢,我有一种预感,JelleWestra 的回答和它会得到的一样好。我会看看我是否可以让.tolist() 为我工作。如果没有totupple(),那肯定是有原因的。 I Do Not Want What I Haven't Got 有 PEP 吗? :-)

标签: python python-3.x numpy multidimensional-array numpy-ndarray


【解决方案1】:

您可以使用一个递归函数,该函数可以转换为与维数无关的元组:

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

在这个答案中找到: Convert numpy array to tuple

【讨论】:

  • 有趣!我会试一试。我希望有“类似于 numpy 的 .tolist().totuple() 方法”,这样我就不必每次需要它时都重写它,但它可能不存在。
  • @uhoh 据我所知,不幸的是,numpy 中不存在这样的方法或函数。
  • 将此函数应用于tolist 结果可能更快。
猜你喜欢
  • 2023-02-03
  • 2020-04-14
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
相关资源
最近更新 更多