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

问题描述:

我有一个包含重复字段的protobuf消息。我想删除列表中的某个项目,但似乎无法找到一个好方法,无需将所有项目从重复字段中复制到列表中,清除重复字段并重新填充。如何从python中的重复protobuf字段中删除项目?

在C++中有一个RemoveLast()功能,但是这似乎并没有出现在Python的API中......

documentation指出的,在包装纸的Protobuf重复字段的对象的行为就像一个常规的Python序列。因此,你应该能够简单地做

del foo.fields[index] 

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

del foo.fields[-1] 
+1

如果你想删除所有重复的字段,使用'del foo.fields [:]' – 2014-05-02 02:42:23

在Python,删除从列表中的元素以这种方式可以这样做:

list.remove(item_to_be_removed) 

del list[index] 
+0

这不是一个Python列表。这是一种自定义类型。删除不是会员。 – Catskul 2013-11-05 19:47:07

+1

@Catskul这实际上作为protobuf 2.6;他们已经将类似pythonic的操作'extend()'和'remove()'添加到'RepeatedCompositeFieldContainer'类型中。 – chase 2014-12-15 23:44:17

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