【问题标题】:Numpy complicated data structureNumpy复杂的数据结构
【发布时间】:2017-03-01 18:20:09
【问题描述】:

我对 python 很陌生。我想做的是从二进制文件中读取一些类似 c 的结构。在创建它们的 c 程序中,这些结构被定义为:

struct B{
    uint16 y;
    uint8 c[SIZE2];
}

struct A{
    uint32 x;
    struct B b[SIZE1];
}

我希望能够使用 NumPy 包函数 fromFile 读取所有 A 结构,但我不知道如何调用正确的 dtype 方法,例如:

record = numpy.dtype([
    ("field1", numpy.uint8),
    ("field2", numpy.uint16),
    ("field3", numpy.uint32)
])

具有如此复杂的数据结构。

你能帮我写吗?提前谢谢!

【问题讨论】:

  • 你看过here吗?我不确定你是否可以这样嵌套,或者至少,我不知道如何。另外,也许this question 是相关的,不确定。

标签: python c numpy


【解决方案1】:

这有点猜测,因为我使用 C 结构的次数不多。

In [125]: SIZE1, SIZE2 = 3,4

In [127]: dtB=np.dtype([('y',np.uint16),('c',np.uint8,(SIZE2,))])
In [128]: np.ones((2,), dtype=dtB)
Out[128]: 
array([(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])], 
      dtype=[('y', '<u2'), ('c', 'u1', (4,))])
In [129]: _.itemsize
Out[129]: 6

在此定义中,此数组的每条记录由 6 个字节组成,y 字段为 2,c 字段为 4。

然后将其嵌套在 A 定义中

In [130]: dtA=np.dtype([('x',np.uint32),('b',dtB,(SIZE1,))])
In [131]: np.ones((2,), dtype=dtA)
Out[131]: 
array([(1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])]),
       (1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])])], 
      dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))])
In [132]: _.itemsize
Out[132]: 22

x 字段的每条记录有 4 个字节,3 个 b 元素有 3*6。

In [133]: __.tobytes()
Out[133]: b'\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01'

并试图让数组更有趣:

In [136]: A['x']=[1,2]
In [139]: A['b']['y'] *= 3
In [141]: A['b']['c'][0]=2
In [142]: A['b']['c'][1]=3
In [143]: A
Out[143]: 
array([(1, [(3, [2, 2, 2, 2]), (3, [2, 2, 2, 2]), (3, [2, 2, 2, 2])]),
       (2, [(3, [3, 3, 3, 3]), (3, [3, 3, 3, 3]), (3, [3, 3, 3, 3])])], 
      dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))])
In [144]: A[0].tobytes()
Out[144]: b'\x01\x00\x00\x00\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02'

这些字节串是否与您的 c 结构一致?

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2020-01-03
    • 2020-07-16
    相关资源
    最近更新 更多