简体   繁体   English

Python和协议缓冲区:如何从重复的消息字段中删除元素

[英]Python and protocol buffer: how to removed an element from a repeated message field

Accordingly to protocol buffer python generated code documentation , I can add a object to a repeated message field this way: 根据协议缓冲区python生成的代码文档 ,我可以通过以下方式将对象添加到重复的消息字段中:

foo = Foo()
bar = foo.bars.add()        # Adds a Bar then modify
bar.i = 15
foo.bars.add().i = 32       # Adds and modify at the same time

but: 但:

  1. how can I remove bar from bars ? 我如何删除barbars

  2. how can I remove the n-th bar element from bars ? 如何从bars删除第n-th bar元素?

It took me more than a few minutes to get the proto buffer compiler installed correctly, so that may be reason enough to ignore this :) 我花了几分钟多的时间才能正确安装原型缓冲区编译器,因此这可能是足以忽略这一点的原因:)

Although it isn't in the documentation, you can actually treat a repeated field much like a normal list. 尽管它不在文档中,但实际上您可以将重复字段视为普通列表。 Aside from its private methods, it supports add , extend , remove and sort , and remove is what you are looking for in the first case: 除了私有方法外,它还支持addextendremovesort ,以及remove是您在第一种情况下要查找的内容:

foo.bars.remove(bar)

Here is the output when printing foo before the above line (as defined by your code above) and after: 这是在上述行之前(由上面的代码定义)和之后打印foo时的输出:

 Original foo: bars { i: 15 } bars { i: 32 } foo without bar: bars { i: 32 } 

As for removing the nth element, you can use del and the index position you want to delete: 至于删除第nth元素,可以使用del和要删除的索引位置:

# Delete the second element
del foo.bars[1]

And the output: 并输出:

 Original foo: bars { i: 15 } bars { i: 32 } Removing index position 1: bars { i: 15 } 

Hope that helps! 希望有帮助!

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

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