Python 构造结构化数组时,元组和列表之间有什么区别?

Python 构造结构化数组时,元组和列表之间有什么区别?,python,python-3.x,numpy,numpy-ndarray,Python,Python 3.x,Numpy,Numpy Ndarray,当我在尝试numpy的结构化数组时,我注意到当我调用 np.array([[1,2],[3,4],[5,6],[7,8]],dtype='i,i')i获得 [[(1, 1), (2, 2)], [(3, 3), (4, 4)], [(5, 5), (6, 6)], [(7, 7), (8, 8)]] ValueError: could not assign tuple of length 4 to structure with 2 fields. 当我打电话的时候 np.array([

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

[[(1, 1), (2, 2)],
 [(3, 3), (4, 4)],
 [(5, 5), (6, 6)],
 [(7, 7), (8, 8)]]
ValueError: could not assign tuple of length 4 to structure with 2 fields.
当我打电话的时候
np.array([1,2],[3,4],[5,6],[7,8]),dtype='i,i')
i get

[[(1, 1), (2, 2)],
 [(3, 3), (4, 4)],
 [(5, 5), (6, 6)],
 [(7, 7), (8, 8)]]
ValueError: could not assign tuple of length 4 to structure with 2 fields.
在这两种情况下,我都应该得到一个正常的
[(1,2)、(3,4)、(5,6)、(7,8)]
数组。 在构造numpy的结构化数组时,元组和列表之间有什么区别

In [36]: dt = np.dtype('i,i')                                                   
In [37]: dt                                                                     
Out[37]: dtype([('f0', '<i4'), ('f1', '<i4')])
此列表,生成匹配形状(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)
我可以将其更改为元组中的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.
[(1,2)、(3,4)、(5,6)、(7,8)]
是2字段数据类型的正确输入(和显示)。文档非常明确地说输入应该是一个元组列表。其他人都错了,导致它要么胡说八道,要么提出错误。对于简单的数据类型,
np.array
将列表和元组视为相同的,但对于复合数据类型,元组用于标记复合元素(记录)的边界。不要马虎。
In [44]: np.array((1,2), dt)                                                    
Out[44]: array((1, 2), dtype=[('f0', '<i4'), ('f1', '<i4')])
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,))])