我有一个包含重复字段的protobuf消息。 我想删除列表中的一个项目,但是似乎找不到一种好的方法来实现这一点,而不必将所有项目从重复字段复制到列表中,清除重复字段,然后重新填充它。
在C++中有一个RemoveLast()
函数,但在python API中似乎没有这个函数...
我有一个包含重复字段的protobuf消息。 我想删除列表中的一个项目,但是似乎找不到一种好的方法来实现这一点,而不必将所有项目从重复字段复制到列表中,清除重复字段,然后重新填充它。
在C++中有一个RemoveLast()
函数,但在python API中似乎没有这个函数...
正如在文档中所提到的,Protobuf中重复字段的对象包装类行为类似于常规的Python序列。因此,您应该能够简单地执行以下操作:
del foo.fields[index]
例如,要删除最后一个元素,del foo.fields[-1]
在Python中,可以通过以下方式从列表中删除元素:
list.remove(item_to_be_removed)
或者
del list[index]
extend()
和remove()
添加到了RepeatedCompositeFieldContainer
类型中。 - chaseconst 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);
del foo.fields[:]
。注意不改变原意,同时让句子更通俗易懂,不提供解释或其他信息。 - George V. Reilly