[英]Get a list from numpy ndarray in Python?
I have a numpy.ndarray here which I am trying to convert it to a list.我这里有一个 numpy.ndarray,我试图将它转换为一个列表。
>>> a=np.array([[[0.7]], [[0.3]], [[0.5]]])
I am using hstack for it.我正在为此使用 hstack。 However, I am getting a list of a list.
但是,我得到了一个列表列表。 How can I get a list instead?
我怎样才能得到一个列表? I am expecting to get
[0.7, 0.3, 0.5]
.我期待得到
[0.7, 0.3, 0.5]
。
>>> b = np.hstack(a)
>>> b
array([[0.7, 0.3, 0.5]])
Do you understand what you have?你明白你拥有的是什么吗?
In [46]: a=np.array([[[0.7]], [[0.3]], [[0.5]]])
In [47]: a
Out[47]:
array([[[0.7]],
[[0.3]],
[[0.5]]])
In [48]: a.shape
Out[48]: (3, 1, 1)
That's a 3d array - count the []那是一个 3d 数组 - 计算 []
You can convert it to 1d with:您可以使用以下方法将其转换为 1d:
In [49]: a.ravel()
Out[49]: array([0.7, 0.3, 0.5])
tolist
converts the array to a list: tolist
将数组转换为列表:
In [50]: a.ravel().tolist()
Out[50]: [0.7, 0.3, 0.5]
You could also use a[:,0,0]
.您也可以使用
a[:,0,0]
。 If you use hstack
, that partially flattens it - but not all the way to 1d.如果您使用
hstack
,它会部分变平 - 但不会一直到 1d。
In [51]: np.hstack(a)
Out[51]: array([[0.7, 0.3, 0.5]])
In [52]: _.shape
Out[52]: (1, 3)
In [53]: np.hstack(a)[0]
Out[53]: array([0.7, 0.3, 0.5])
Alternatively, numpy.ndarray.flatten
can be used:或者,可以使用
numpy.ndarray.flatten
:
a.flatten().tolist()
And yet another possibility:还有另一种可能性:
a.reshape(-1).tolist()
Output:输出:
[0.7, 0.3, 0.5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.