[英]Why numpy requires list of tuples and not list of lists?
I'm creating table with information about images:我正在创建包含有关图像信息的表:
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)
When instead of list of tuples I create list of lists当我创建列表列表而不是元组列表时
filedesc = (name, ext, size, size/1024)
I get an error我收到一个错误
ValueError: invalid literal for int() with base 10: 'somefilename'
Why is that?这是为什么?
Here's an example, with several levels of nesting of [] and ().这是一个示例,其中包含多个级别的 [] 和 () 嵌套。
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')]]
And another with a compound dtype within a compound dtype:另一个在复合 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')])])
At each level, the use of () versus [] conveys useful information.在每个级别,() 与 [] 的使用都传达了有用的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.