在构造结构化数组时,tuple和list之间有什么区别?

问题描述 投票:2回答:1

当我在试验numpy的结构化数组时,我注意到当我调用np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype='i, i') 我得到

[[(1, 1), (2, 2)],
 [(3, 3), (4, 4)],
 [(5, 5), (6, 6)],
 [(7, 7), (8, 8)]]

而当我打电话np.array(([1, 2], [3, 4], [5, 6], [7, 8]), dtype='i, i') 我得到

ValueError: could not assign tuple of length 4 to structure with 2 fields.

而在这两种情况下,我应该已经得到了一个正常的。[(1, 2), (3, 4), (5, 6), (7, 8)] 构建numpy的结构化数组时,tuple和list有什么区别?

python python-3.x numpy numpy-ndarray
1个回答
3
投票
In [36]: dt = np.dtype('i,i')                                                   
In [37]: dt                                                                     
Out[37]: dtype([('f0', '<i4'), ('f1', '<i4')])

用一个元组列表进行正确的创建,其中每个元组的大小(和类型)相匹配。dtype:

In [38]: np.array([(1, 2), (3, 4), (5, 6), (7, 8)], dt)                         
Out[38]: 
array([(1, 2), (3, 4), (5, 6), (7, 8)],
      dtype=[('f0', '<i4'), ('f1', '<i4')])
In [39]: print(_)                                                               
[(1, 2) (3, 4) (5, 6) (7, 8)]

这个列表,使一个匹配形状的数组(4,2),并将一个值分配给两个字段。

In [40]: np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dt)                         
Out[40]: 
array([[(1, 1), (2, 2)],
       [(3, 3), (4, 4)],
       [(5, 5), (6, 6)],
       [(7, 7), (8, 8)]], dtype=[('f0', '<i4'), ('f1', '<i4')])
In [41]: _.shape                                                                
Out[41]: (4, 2)

这里的 () 被解释为标记一条记录。 但它有4个元素,而dtype只需要2个元素。

In [42]: np.array(([1, 2], [3, 4], [5, 6], [7, 8]), dt)                         
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-42-730c344e4f84> in <module>
----> 1 np.array(([1, 2], [3, 4], [5, 6], [7, 8]), dt)

ValueError: could not assign tuple of length 4 to structure with 2 fields.

我可以在元组中把它改成2个元素,但它们的类型是错误的,每个元素有2个值,而不是1个。

In [43]: np.array(([1, 2], [3, 4]), dt)                                         
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-43-976803c7a6c9> in <module>
----> 1 np.array(([1, 2], [3, 4]), dt)

ValueError: setting an array element with a sequence.

在这种情况下,元组确实可以工作 - 制作一个0d结构化数组(1个元素)。

In [44]: np.array((1,2), dt)                                                    
Out[44]: array((1, 2), dtype=[('f0', '<i4'), ('f1', '<i4')])

[43] 可以用不同的 dtype其中,每个字段期望有两个值。

In [46]: np.array(([1, 2], [3, 4]), [('f0','i',2),('f1','f',2)])                
Out[46]: array(([1, 2], [3., 4.]), dtype=[('f0', '<i4', (2,)), ('f1', '<f4', (2,))])
© www.soinside.com 2019 - 2024. All rights reserved.