You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Python中为Protobuf2重复基本类型字段赋值遇阻求助

问题解决方法

首先纠正两处关键问题:

  1. Proto定义笔误:你的X消息中repeated B b = 2;的B未定义,结合代码逻辑,应该改为repeated BtoOtherBEntry b = 2;,否则无法通过x.b.add()得到包含parent_b和children_b的对象。
  2. Python语法错误:实例化X对象时,正确写法是x = X(),而非X x。

针对children_b字段的赋值,以下几种方法都可以正常工作:

方法1:使用extend(推荐)

确保values是整数列表,直接调用extend批量添加元素:

x = X()
for key, values in self.BtoBMap.items():
    if len(values) > 0:
        b_to_b_entry = x.b.add()
        b_to_b_entry.parent_b = key
        b_to_b_entry.children_b.extend(values)

如果values中的元素类型不是整数(比如是字符串),需要先转换:

b_to_b_entry.children_b.extend(int(val) for val in values)

方法2:循环append

逐个添加元素,适合需要对每个元素做额外处理的场景:

x = X()
for key, values in self.BtoBMap.items():
    if len(values) > 0:
        b_to_b_entry = x.b.add()
        b_to_b_entry.parent_b = key
        for val in values:
            b_to_b_entry.children_b.append(val)

方法3:切片赋值

直接替换整个children_b列表,效果和extend一致:

x = X()
for key, values in self.BtoBMap.items():
    if len(values) > 0:
        b_to_b_entry = x.b.add()
        b_to_b_entry.parent_b = key
        b_to_b_entry.children_b[:] = values

内容的提问来源于stack exchange,提问作者Hadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:15:10