为什么numpy需要元组列表而不是列表列表?

时间:2019-12-06 16:49:31

标签: python numpy

我正在创建有关图像信息的表:

directory = 'images'
dtype = [
    ('file', np.str_), 
    ('ext', np.str_), 
    ('size', np.int32), 
    ('sizeKB', np.float), 
]
files = []

for file in os.listdir(directory):
    height = 0
    width = 0 
    filepath = os.path.join(directory, file)

    name, ext = os.path.splitext(filepath)
    name = name[7:]
    size = os.path.getsize(filepath)

    filedesc = (name, ext, size, size/1024)
    files.append(filedesc)

files_np = np.array(files, dtype=dtype)

何时创建元组列表而不是元组列表

filedesc = (name, ext, size, size/1024)

我遇到错误

ValueError: invalid literal for int() with base 10: 'somefilename'

那是为什么?

1 个答案:

答案 0 :(得分:0)

这里是一个示例,其中[[]和()的嵌套多层。

In [32]: dt = np.dtype([('x',int,3),('y','U10')])                               
In [33]: data = np.zeros((3,2),dt)                                              
In [34]: data                                                                   
Out[34]: 
array([[([0, 0, 0], ''), ([0, 0, 0], '')],
       [([0, 0, 0], ''), ([0, 0, 0], '')],
       [([0, 0, 0], ''), ([0, 0, 0], '')]],
      dtype=[('x', '<i8', (3,)), ('y', '<U10')])

In [36]: data['x']=np.arange(18).reshape(3,2,3)                                 
In [37]: data['y']='foobar'                                                     
In [38]: data                                                                   
Out[38]: 
array([[([ 0,  1,  2], 'foobar'), ([ 3,  4,  5], 'foobar')],
       [([ 6,  7,  8], 'foobar'), ([ 9, 10, 11], 'foobar')],
       [([12, 13, 14], 'foobar'), ([15, 16, 17], 'foobar')]],
      dtype=[('x', '<i8', (3,)), ('y', '<U10')])
In [39]: print(data)                                                            
[[([ 0,  1,  2], 'foobar') ([ 3,  4,  5], 'foobar')]
 [([ 6,  7,  8], 'foobar') ([ 9, 10, 11], 'foobar')]
 [([12, 13, 14], 'foobar') ([15, 16, 17], 'foobar')]]

另一个在化合物dtype中具有化合物dtype的

In [41]: np.zeros(2,dt)                                                         
Out[41]: 
array([([0, 0, 0], (0, 0.)), ([0, 0, 0], (0, 0.))],
      dtype=[('x', '<i8', (3,)), ('y', [('f0', '<i8'), ('f1', '<f8')])])

在每个级别,使用()和[]都可以传达有用的信息。

相关问题