访问python中的google protobuf文件(简单)

时间:2016-04-27 20:23:35

标签: python arrays list protocol-buffers

我从protobuf文件中读取消息。 该消息包含时间序列数据,因此,我预期类似矩阵的结构,例如processed_row [nData,nVar]

print(mySerializedData.processed_row)
>> [timestamp: 0.0
linear_acc_x: 0.288501300049
linear_acc_y: 0.573411297607
linear_acc_z: 0.161608612061
, timestamp: 0.0049
linear_acc_x: 0.428562097168
linear_acc_y: 0.685938775635
linear_acc_z: 0.221463653564
, timestamp: 0.01
linear_acc_x: 0.45968671875
linear_acc_y: 0.738611212158
linear_acc_z: 0.185550628662]

我可以访问个人数据,如

print(mySerializedData.processed_row[0].timestamp)
>> 0.0
print(mySerializedData.processed_row[1].timestamp)
>> 0.0049

但我想要获得的是

print(mySerializedData.processed_row[:].timestamp)

但它显示错误AttributeError: 'list' object has no attribute 'timestamp'

print(type(mySerializedData.processed_row[0].timestamp))
>> <type 'float'>
print(type(mySerializedData.processed_row[0]))
>> <class 'PushCore_pb2.ProcessedDataRow'>

有没有办法像[[]]一样得到timestamp双数组?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用list comprehension

创建时间戳值列表
[element.timestamp for element in mySerializedData.processed_row]

这是一个概括性的例子。在example.proto

package example;

message Element {
  required double timestamp = 1;
  required string data = 2;
}

message Container {
  repeated Element elements = 1;
}

使用:

生成相应的Python输出
protoc --python_out=. example.proto

然后,在Python中:

>>> from example_pb2 import Container, Element
>>> 
>>> container = Container(
...   elements=[
...     Element(timestamp=.1, data='Some data.'),
...     Element(timestamp=.2, data='Some more data.'),
...   ]
... )
>>> 
>>> [element.timestamp for element in container.elements]
[0.1, 0.2]