gpt4 book ai didi

Python 和 Protocol Buffer : how to removed an element from a repeated message field

转载 作者:行者123 更新时间:2023-11-28 22:58:36 33 4
gpt4 key购买 nike

根据protocol buffer python generated code documentation ,我可以通过这种方式将对象添加到重复的消息字段:

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

但是:

  1. 如何从 bars 中删除 bar

  2. 如何从 bars 中删除第 n-th 条形元素?

最佳答案

我花了几分钟才正确安装了 proto buffer 编译器,所以这可能足以忽略这个 :)

虽然它不在文档中,但您实际上可以像处理普通列表一样处理重复字段。除了私有(private)方法外,它还支持addextendremovesort,以及remove 是您在第一种情况下要查找的内容:

foo.bars.remove(bar)

这是在上面一行(由上面的代码定义)之前和之后打印 foo 时的输出:

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

foo without bar:
bars {
i: 32
}

关于删除nth元素,可以使用del和要删除的索引位置:

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

输出:

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

Removing index position 1:
bars {
i: 15
}

希望对您有所帮助!

关于Python 和 Protocol Buffer : how to removed an element from a repeated message field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13726394/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com