如何在Python中从重复的protobuf字段中删除项目?

20

我有一个包含重复字段的protobuf消息。 我想删除列表中的一个项目,但是似乎找不到一种好的方法来实现这一点,而不必将所有项目从重复字段复制到列表中,清除重复字段,然后重新填充它。

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

3个回答

26

正如在文档中所提到的,Protobuf中重复字段的对象包装类行为类似于常规的Python序列。因此,您应该能够简单地执行以下操作:

del foo.fields[index]
例如,要删除最后一个元素,
del foo.fields[-1]

8
如需删除所有重复字段,请使用del foo.fields[:]。注意不改变原意,同时让句子更通俗易懂,不提供解释或其他信息。 - George V. Reilly

2

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

list.remove(item_to_be_removed)

或者

del list[index]

这不是 Python 列表,而是自定义类型。Remove 不是其中的成员。 - Catskul
1
@Catskul,这在protobuf 2.6中实际上是可行的;他们已经将类似于Python列表的操作extend()remove()添加到了RepeatedCompositeFieldContainer类型中。 - chase

-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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接