20

我有一个包含重复字段的 protobuf 消息。我想删除列表中的一个项目,但如果不将重复字段中的所有项目复制到列表中,清除重复字段并重新填充它,我似乎找不到这样做的好方法。

在 C++ 中有一个RemoveLast()函数,但这似乎没有出现在 python API 中......

4

3 回答 3

23

文档中所述,在 Protobuf 中包装重复字段的对象的行为类似于常规 Python 序列。因此,你应该能够简单地做

del foo.fields[index]

例如,要删除最后一个元素,

del foo.fields[-1]
于 2013-03-09T07:17:19.290 回答
2

在 Python 中,可以通过以下方式从列表中删除元素:

list.remove(item_to_be_removed)

或者

del list[index]
于 2013-03-09T04:34:53.767 回答
0
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);
于 2014-04-04T03:23:28.107 回答