Python 如何分配给重复字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23726335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign to repeated field?
提问by PaolaJ.
I am using protocol buffers in python and I have a Person
message
我在 python 中使用协议缓冲区,我有一条Person
消息
repeated uint64 id
but when I try to assign a value to it like:
但是当我尝试为它分配一个值时:
person.id = [1, 32, 43432]
I get an error: Assigment not allowed for repeated field "id" in protocol message object
How to assign a value to a repeated field ?
我收到一个错误:Assigment not allowed for repeated field "id" in protocol message object
如何为重复字段赋值?
采纳答案by Tim
As per the documentation, you aren't able to directly assign to a repeated field. In this case, you can call extend
to add all of the elements in the list to the field.
根据文档,您无法直接分配给重复字段。在这种情况下,您可以调用extend
将列表中的所有元素添加到字段中。
person.id.extend([1, 32, 43432])
回答by kirpit
If you don't want to extendbut overwrite it completely, you can do:
如果你不想扩展而是完全覆盖它,你可以这样做:
person.id[:] = [1, 32, 43432]
This approach will also work to clear the field entirely:
这种方法也将有助于彻底清除该领域:
del person.id[:]
回答by Nicholas Gentile
You can try using MergeFrom
您可以尝试使用 MergeFrom
Check out these docs for the full list of Message methods available to you: https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.message.Message-class
查看这些文档以获取可用的 Message 方法的完整列表:https: //developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.message.Message-class
回答by Chandler
For repeated composite types this is what worked for me.
对于重复的复合类型,这对我有用。
del person.things[:]
person.things.extend([thing1, thing2, ..])
taken from these comments How to assign to repeated field?How to assign to repeated field?
取自这些评论 如何分配给重复的字段?如何分配给重复字段?