简体   繁体   English

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

[英]How can I remove an item from a repeated protobuf field in python?

I have a protobuf message that contains a repeated field. 我有一个包含重复字段的protobuf消息。 I would like to remove one of the items in the list but I can't seem to find a good way to do so without copying all of the items out of the repeated field into a list, clearing the repeated field, and repopulating it. 我想删除列表中的一个项目,但我似乎无法找到一个好方法,不将重复字段中的所有项目复制到列表中,清除重复字段,然后重新填充它。

In C++ there is a RemoveLast() function, but this doesn't seem to appear in the python API... 在C ++中有一个RemoveLast()函数,但这似乎没有出现在python API中......

As noted in the documentation , the object wrapping a repeated field in Protobuf behaves like a regular Python sequence. 文档中所述,Protobuf中包含重复字段的对象的行为类似于常规Python序列。 Therefore, you should be able to simply do 因此,你应该能够做到

del foo.fields[index]

For example, to remove the last element, 例如,要删除最后一个元素,

del foo.fields[-1]

In Python, deleting an element from a list could be done in this way: 在Python中,可以通过以下方式从列表中删除元素:

list.remove(item_to_be_removed)

or 要么

del list[index]
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM