簡體   English   中英

使用python訪問Google protobuf文件(簡單)

[英]Access to google protobuf files in python (easy)

我從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雙精度數組?

謝謝

您可以使用列表推導來創建時間戳記值的列表

[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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM