如何将元组列表转换为 numpy 元组数组?

编程入门 行业动态 更新时间:2024-10-28 06:23:22
本文介绍了如何将元组列表转换为 numpy 元组数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个这样的列表:

l=[(1,2),(3,4)]

我想将它转换为一个 numpy 数组,并将数组项类型保留为元组:

I want to convert it to a numpy array,and keep array item type as tuple:

array([(1,2),(3,4)])

但 numpy.array(l) 会给出:

but numpy.array(l) will give:

array([[1,2],[3,4)]])

并且项目类型已从元组更改为numpy.ndarray,然后我指定了项目类型

and item type has been changed from tuple to numpy.ndarray,then I specified item types

numpy.array(l,numpy.dtype('float,float'))

这给出:

array([(1,2),(3,4)])

但项目类型不是元组而是numpy.void,所以问题是:

but item type isn't tuple but numpy.void,so question is:

how to convert it to a numpy.array of tuple,not of numpy.void?

推荐答案

你可以有一个 object dtype 的数组,让数组的每个元素都是一个元组,就像这样 -

You can have an array of object dtype, letting each element of the array being a tuple, like so -

out = np.empty(len(l), dtype=object) out[:] = l

样品运行 -

In [163]: l = [(1,2),(3,4)] In [164]: out = np.empty(len(l), dtype=object) In [165]: out[:] = l In [172]: out Out[172]: array([(1, 2), (3, 4)], dtype=object) In [173]: out[0] Out[173]: (1, 2) In [174]: type(out[0]) Out[174]: tuple

更多推荐

如何将元组列表转换为 numpy 元组数组?

本文发布于:2023-07-13 03:25:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1099799.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   如何将   列表   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!