我有一个json文件,比如:
{
"parentNode": {
"id": "root",
"mbs": [
16995.9859862176,
-6029.919928079834,
-4.6344976928710935,
4674.872691701428
]
},
"children": [
{
"id": "00t2",
"mbs": [
16561.761031809023,
-5189.992543469676,
5,
221.7414398051216
]
},
{
"id": "01t2",
"mbs": [
16851.244334748077,
-5189.992543469676,
5,
221.7414398051216
]
}
]
}
现在我想更改mbs值,但是在回滚之前需要一个日志。你知道吗
所以我的代码是:
if jsondict['parentNode']:
mbsx=jsondict['parentNode']['mbs'][0]
mbsy=jsondict['parentNode']['mbs'][1]
nodeid=jsondict['parentNode']['id'] #log the node id and mbs value
jsondict['mymbs_parent']=[nodeid,mbsx,mbsy] #write em down
jsondict['parentNode']['mbs'][0]=mbsx+xoffset #then change the value
jsondict['parentNode']['mbs'][1]=mbsy+yoffset
这对父节点很好
但是可能有许多子节点,因此对于子节点部分,代码如下所示:
if jsondict['children']:
count=len(jsondict['children'])
for i in range(count):
mbsx=jsondict['children'][i]['mbs'][0]
mbsy=jsondict['children'][i]['mbs'][1]
nodeid=jsondict['children'][i]['id']
jsondict['mymbs_children'][i]=(nodeid,mbsx,mbsy)
jsondict['children'][i]['mbs'][0]=mbsx+xoffset
jsondict['children'][i]['mbs'][1]=mbsy+yoffset
然后我得到list assignment index out of range
错误。你知道吗
我想json文件中还没有mymbs_children
,所以没有jsondict['mymbs_children'][i]
我还不知道怎么做,有什么想法吗?你知道吗
您可以在
if
循环周围放置一个for
条件来检查:对于python3.8以后的版本,还可以使用walrus操作符来减少代码行数:(for more info)
我更喜欢的另一种方式是不使用
range
:这将避免超出范围索引的问题,您甚至可能不需要使用
count
变量我不喜欢你的方法,但为了简单起见,我可以回答你提出的问题。若要修复出现的错误,请添加
作为后面的第一行
这将创建一个列表,然后您将尝试写入该列表。你知道吗
然后需要使用
.append()
将项目添加到列表中:而不是
相关问题 更多 >
编程相关推荐