【问题标题】:How can I remove an item from a repeated protobuf field in python?如何从 python 中重复的 protobuf 字段中删除项目?
【发布时间】:2013-03-09 04:16:34
【问题描述】:

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

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

【问题讨论】:

    标签: python protocol-buffers


    【解决方案1】:

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

    del foo.fields[index]
    

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

    del foo.fields[-1]
    

    【讨论】:

    • 如果要删除所有重复的字段,请使用del foo.fields[:]
    【解决方案2】:

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

    list.remove(item_to_be_removed)
    

    del list[index]
    

    【讨论】:

    • 这不是 python 列表。它是一种自定义类型。删除不是成员。
    • @Catskul 这实际上适用于 protobuf 2.6;他们在RepeatedCompositeFieldContainer 类型中添加了类似pythonic 的列表操作extend()remove()
    【解决方案3】:
    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 2017-01-22
      • 2021-01-22
      • 2016-03-13
      • 2011-09-29
      • 2013-08-03
      • 2016-08-28
      相关资源
      最近更新 更多