如何从python中的重复protobuf字段中删除项目?
问题描述:
我有一个包含重复字段的protobuf消息。我想删除列表中的某个项目,但似乎无法找到一个好方法,无需将所有项目从重复字段中复制到列表中,清除重复字段并重新填充。如何从python中的重复protobuf字段中删除项目?
在C++中有一个RemoveLast()
功能,但是这似乎并没有出现在Python的API中......
答
如documentation指出的,在包装纸的Protobuf重复字段的对象的行为就像一个常规的Python序列。因此,你应该能够简单地做
del foo.fields[index]
例如,删除最后一个元素,
del foo.fields[-1]
答
const google::protobuf::Descriptor *descriptor = m_pMessage->GetDescriptor();
const google::protobuf::Reflection *reflection = m_pMessage->GetReflection();
const google::protobuf::FieldDescriptor* field = descriptor->FindFieldByName("my_list_name");
if (i<list_size-1)
{
reflection->SwapElements(m_pMessage, field, i, list_size-1);
}
reflection->RemoveLast(m_pMessage, field);
+5
答案显然要求Python API ... – nneonneo 2014-04-06 03:21:19
如果你想删除所有重复的字段,使用'del foo.fields [:]' – 2014-05-02 02:42:23