Python字典中为何不允许使用+=增量运算符?代码报错咨询
为什么字典内不能使用+=增量运算符?
这是Python的语法规则限制:+=这类增量赋值属于语句,不是表达式。语句的作用是执行操作(比如修改变量的值),但不会返回任何可供直接使用的值;而字典的键值对中,冒号右侧必须是能计算出具体结果的表达式——你不能把一个执行操作的语句当作值来赋值给字典的键。
你写的"id": id_count += 1本质是试图把赋值语句塞进值的位置,Python解释器会直接判定这是语法错误,根本无法执行。
解决办法
你可以把递增操作和字典创建分开,有两种常见写法:
写法1:先完成递增再赋值
for i in range(0, len(all_locations)): id_count += 1 object_sequence_count += 1 # 先计算location需要的id并递增计数器 loc_id = id_count + 1 id_count = loc_id object_data_output = { "id": id_count - 1, # 对应外层的id值 "sequence": object_sequence_count, "coordinate":{ "x": all_locations[i]["coordinate"]["x"], "y": all_locations[i]["coordinate"]["y"], "objIdentifier": all_locations[i]["materialIdentifier"], "location":[ { "id": loc_id } ] } }
写法2:用表达式计算值,最后统一递增计数器
for i in range(0, len(all_locations)): id_count += 1 object_sequence_count += 1 object_data_output = { "id": id_count, "sequence": object_sequence_count, "coordinate":{ "x": all_locations[i]["coordinate"]["x"], "y": all_locations[i]["coordinate"]["y"], "objIdentifier": all_locations[i]["materialIdentifier"], "location":[ { "id": id_count + 1 # 直接用表达式计算值,不修改计数器 } ] } } id_count += 1 # 最后统一递增计数器
内容的提问来源于stack exchange,提问作者marsprogrammer
相关产品推荐
相关产品推荐

